var brushImg = new Image();
brushImg.src = 'data:image/png;base64,' + config.brushImg;  
var skin = window.skin ||{};
var giftLen = 0;   // 用于暂存礼品中心长度
//var giftObj = null;
var timer = 0;

/**
 * 获取元素对象
 * @param  {string} element 元素id
 * @return {object}         返回元素对象
 */
skin.g = function(element) {
    return document.getElementById(element) || element;
};


skin.getElementsClass = function (classnames) {

    var classobj = new Array();//定义数组

    var classint = 0;//定义数组的下标

    var tags = document.getElementsByTagName("*");//获取HTML的所有标签

    for(var i in tags){ //对标签进行遍历

        if(tags[i].nodeType==1){//判断节点类型
            if(tags[i].getAttribute("class") == classnames)//判断和需要CLASS名字相同的，并组成一个数组
            {
                classobj[classint] = tags[i];
                classint++;
            }

        }

    }

    return classobj;//返回组成的数组
};
/**
 * 转换JSON对象
 * @param  {string} jsonString json字符串
 * @return {object}            json对象
 */
skin.jsonDecode =function(jsonString) {
	return (new Function("return " + jsonString))();
};
/**
 * 显示dom
 * @param  {string} id dom的id
 * @return {void}    无
 */

skin.show = function(id) {
	skin.isShow(id, true);
};
/**
 * 隐藏dom
 * @param  {string} id dom的id
 * @return {void}    无
 */
skin.hide = function(id) {
    skin.isShow(id, false);
};
/**
 * 是否显示
 * @return {Boolean} 返回布尔值
 */
skin.isShow = function(id, flag) {
    skin.g(id).style.display = flag ? 'block' : 'none';
};
/**
 * 添加样式
 * @param {string|object} element   目标元素
 * @param {string} className 样式名称
 */
skin.addClass = function(element, className) { 
	element = skin.g(element)||element;
    var classArray = className.split(/\s+/),
        result = element.className,
        classMatch = " " + result + " ",
        i = 0,
        l = classArray.length;

    for (; i < l; i++) {
         if ( classMatch.indexOf( " " + classArray[i] + " " ) < 0 ) {
             result += (result ? ' ' : '') + classArray[i];
         }
    }

    element.className = result;
};
/**
 * 移除样式
 * @param  {string|object} element   目标元素
 * @param  { } className 样式名称
 * @return {void}           无
 */
skin.removeClass = function(element, className) { 
	element = skin.g(element)||element; 

    var oldClasses = element.className.split(/\s+/),
        newClasses = className.split(/\s+/),
        lenOld,
        lenDel = newClasses.length,
        j,
        i = 0;  
    for (; i < lenDel; ++i) {
        for(j = 0, lenOld = oldClasses.length; j < lenOld; ++j) {
            if (oldClasses[j] == newClasses[i]) {
            	oldClasses.splice(j, 1);
            	break;
            }
        }
    }
    element.className = oldClasses.join(' ');
};
skin.addEvent = function (obj, type, fn) {
    var isFirefox = typeof document.body.style.MozUserSelect != 'undefined'; 
    if(obj.addEventListener) {
        obj.addEventListener(isFirefox ? 'DOMMouseScroll' : type, fn, false); 
    } else {
        obj.attachEvent('on'+type, fn); 
    }         
    return fn;
};
skin.delEvent = function (obj, type, fn) { 
    var isFirefox = typeof document.body.style.MozUserSelect != 'undefined'; 
    if(obj.removeEventListener) {
        obj.removeEventListener(isFirefox ? 'DOMMouseScroll' : type, fn, false); 
    } else {
        obj.detachEvent('on'+type, fn); 
    }    
};
skin.stopEvent = function (e) {
    e = e||event; 
    if( e.preventDefault )e.preventDefault(); 
    e.returnValue = false;
};
skin.getWheelValue = function (e) { 
    e = e||event; 
    return ( e.wheelDelta ? e.wheelDelta/120 : -( e.detail%3 == 0 ? e.detail/3 : e.detail ) ) ; 
};
/**
 * 把数字转成字符串并加入逗号，如 1,234,567.89
 * @param num
 * @returns {string}
 */
skin.addComma = function (num) {
    var nStr = num + '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
};
/**
 * 执行命令
 * @param {string} order 命令名称
 * @param {string} key 值
 * @return string | void
 */
skin.execOrder = function (order, key) {
    var info = '';
    try { 
        key = (!key ? 'null' : key); 
        info = window.external.SyncRequest(order, key);
    } catch (e) {       
    } 
    return info;
};
/**
 * 最小化当前窗口
 */
skin.minimizeWind = function (id) {
    skin.g(id).onmouseup = function () { 
        skin.addClass(id,"nohover");
        skin.execOrder('minimizeApp');
    };

    skin.g(id).onmouseover = function () {
        skin.removeClass(id,"nohover");
    };
};
/**
 * 关闭当前窗口
 */
skin.closeWind = function (id) {
    skin.g(id).onmouseup = function () {
        skin.execOrder('closeApp');
    }
};
/**
 * 领奖品
 */
skin.getAward = function () {
    var awardParam = {needLogin: false, url: config.getAward};
    skin.execOrder('openUrl', JSON.stringify(awardParam)); 
};
/**
 * 初始化
 */
skin.initIme = function () {

};
/**
 * 在一支笔中打印日志
 * @param {string} str 打印的内容
 */
function Log(str) {   
    try {
        if(window.external.SyncRequest) { 
            window.external.SyncRequest('log', str);
        } else {   //在浏览器控制台中输出        
            console.log(str);
        }
    } catch (e) {}
}
/**
 * 获取点纵坐标
 * @param  {Number} total    当天输入总量
 * @param  {Number} maxTotal 最高输入总量记录
 * @return {Number}          坐标值
 */
function getPointY(total, maxTotal) {
    var max = maxTotal || 1;
    return Math.floor((max - total) / max * (config.table.height - 8)) + 4;
}
/**
 * 获取点横坐标
 * @param  {Number} day    第N天
 * @param  {Number} dayLen 总天数
 * @return {Number}        坐标值
 */
function getPointX(day, dayLen) {
    return Math.floor((6 - day) / 6 * (config.table.width - 8)) + 4;
}
/**
 * 绘制文字输入数量折线图
 * @param  {object} oCanvas   canvas对象
 * @param  {object} inputList 7天文字输入记录
 * @param  {number} maxVal    28天单天输入文字最高纪录
 */
function buildTable (oCanvas, inputList, maxVal) {
    skin.pointList = [];
    oCanvas = oCanvas || skin.g('inputTableCanvas'); 
    var oCtx = oCanvas.getContext("2d");    
    var canvasParent = oCanvas.parentElement;
    oCtx.clearRect(0, 0, oCtx.canvas.width, oCtx.canvas.height);   
    //canvasParent.removeChild(skin.g('bgCanvas'));

    var dLen = inputList.length - 1;
    var oPoint = {
        iX: 0,
        iY: 0
    };

    oCtx.beginPath();
    oCtx.strokeStyle = "#228ee6";
    oCtx.lineWidth = 2;

    oPoint.iX = getPointX(0, dLen);
    oPoint.iY = getPointY(inputList[0].total, maxVal);
    oCtx.moveTo(oPoint.iX, oPoint.iY);
    skin.pointList.push({iX: oPoint.iX, iY: oPoint.iY});
    for (var i = 1, iLen = inputList.length; i < iLen; i++) {
        oPoint.iX = getPointX(i, dLen);
        oPoint.iY = getPointY(inputList[i].total, maxVal);

        oCtx.lineTo(oPoint.iX, oPoint.iY);

        skin.pointList.push({iX: oPoint.iX, iY: oPoint.iY});   
    }
    oCtx.stroke();

    // 绘制圆形的结点
    oCtx.fillStyle = "#ffffff";
    for (i = 0, iLen = inputList.length; i < iLen; i++) {
        oCtx.beginPath();
        oPoint.iX = getPointX(i, dLen);
        oPoint.iY = getPointY(inputList[i].total, maxVal);

        oCtx.arc(oPoint.iX, oPoint.iY, 2, 0, 2*Math.PI);

        oCtx.fill();
        oCtx.stroke();
    }

    //canvasParent.appendChild(createTableBg('bgCanvas'));
    // 初始化趋势图时显示为当天输入详情
    showDataInfo(0, inputList);
    tableInfo(oCanvas, inputList);
    // 初始化标尺
    setGaugeText(inputList);
    // 画趋势图背景
    //drawTableBg();
}
/**
 * 文字输入折线图hover显示
 * @param  {object} oCanvas    canvas对象
 * @param  {object} inputList   7天文字输入记录
 */
function tableInfo (oCanvas, inputList) {
    skin.g("mouseEventMask").onmousemove = function (e) {
        e = window.event ? window.event : e;        
        var mouseX = e.clientX - skin.canvasLeft - 170;
        skin.showInfo = false;
        var dataInfo = skin.g('dataInfo');
        var hrPoint = skin.g('hrPoint');
        var k = -1;
        for (var i = 0, iLen = skin.pointList.length; i < iLen; i++) {
            if (mouseX >= skin.pointList[i].iX - 24 && mouseX <= skin.pointList[i].iX + 24) {
                skin.showInfo = true; 
                k = i;
            } 
        }
        if (skin.showInfo && k > -1) {
            showDataInfo(k, inputList);
            skin.showInfo = false;
        } else {
            skin.showInfo = false; 
        }
        
        skin.hoverInfo = true;
        
    };
    // 鼠标移出趋势图区域，显示当天数据详情
    skin.g("mouseEventMask").onmouseout = function() {
        showDataInfo(0, inputList);
    };
}
function showDataInfo (k, inputList) {
    var dataInfo = skin.g('dataInfo');
    var dataInfoText = skin.g('dataInfoText');
    var hrPoint = skin.g('hrPoint');
    var dataInfoPosition = {w: 0, h: 32, paddingLeft: 10};
    dataInfoText.innerHTML = skin.addComma(inputList[k].total);
    dataInfoPosition.w = skin.addComma(inputList[k].total).length * 7 + 21;

    // 在结点上方
    /*skin.removeClass(dataInfo, 'data-info-left');
    skin.removeClass(dataInfo, 'data-info-right');
    skin.addClass(dataInfo, 'data-info-top');
    dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h - 14) + 'px';
    dataInfo.style.left = (skin.pointList[k].iX + config.table.left - (dataInfoPosition.w + dataInfoPosition.paddingLeft * 2) / 2) + 'px';*/

    if (k <= 3) {
        // 在结点左侧
        skin.removeClass(dataInfo, 'data-info-top');
        skin.removeClass(dataInfo, 'data-info-right');
        skin.addClass(dataInfo, 'data-info-left');
        dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h / 2 - 28) + 'px';
        dataInfo.style.left = (skin.pointList[k].iX + config.table.left - (dataInfoPosition.w + dataInfoPosition.paddingLeft * 2) - 16 ) + 'px';
    } else {
        // 在结点右侧
        skin.removeClass(dataInfo, 'data-info-top');
        skin.removeClass(dataInfo, 'data-info-left');
        skin.addClass(dataInfo, 'data-info-right');
        dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h / 2 - 32) + 'px';
        dataInfo.style.left = (skin.pointList[k].iX + config.table.left + 16) + 'px';
    }

    dataInfoText.style.width = dataInfoPosition.w + 'px';
    skin.show('dataInfo');

    //var hrPointH = (config.table.height - skin.pointList[k].iY + 7);
    //hrPoint.style.height = (hrPointH < 5 ? 9 : hrPointH) + 'px';
    hrPoint.style.top = (skin.pointList[k].iY + config.table.top - 38) + 'px';
    hrPoint.style.left = (skin.pointList[k].iX + config.table.left - 8) + 'px';
    //hrPoint.getElementsByTagName('p')[1].style.height = (config.table.height - skin.pointList[k].iY - 2) + 'px';
    skin.show('hrPoint');
}

/**
 * 获取canvas在页面的左坐标
 * @param  {object} obj    canvas对象
 */
function getCanvasPositionX (obj) {
    var curLeft = 0;
    if (obj.offsetParent) { 
        while (obj.offsetParent) {
            curLeft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curLeft += obj.x;
    }

    skin.canvasLeft = curLeft;

   // skin.g('dd').innerHTML = skin.canvasLeft;
}
/**
 * 设置标尺显示
 * @param  {object} inputList   7天文字输入记录
 */
function setGaugeText (inputList) {
    var domList = skin.g("chartGaugeText").getElementsByTagName("p");
    for (var i = 0; i < 7; i ++) {
        if (inputList && inputList[6-i]) {
            domList[i].innerHTML = inputList[6-i].date;
        } else {
            domList[i].innerHTML = "";
        }
    }
}

function setDashboard(speed) {
    var maxSpeed = 960; // 最高速度
    var minDeg = -122; // 0速度的旋转角度
    var maxDeg = 122; // 最高速度的旋转角度
    var speedDive = [0, 10, 60, 200, 500, 960]; // 速度表区间的划分
    var i, len;
    var birdDom = skin.g("maxInputBird");
    var deg = 0, diveDeg;
    if (speed <= 0) {
        deg = minDeg;
    } else if (speed >= maxSpeed) {
        deg = maxDeg;
    } else {
        for (i = 0, len = speedDive.length; i < len; i ++) {
            if (speedDive[i] >= speed) {
                break;
            }
        }
        diveDeg = (maxDeg - minDeg) / (len-1);
        deg = (speed - speedDive[i-1]) / (speedDive[i] - speedDive[i-1]) * diveDeg + minDeg + diveDeg * (i-1);
    }
    birdDom.style.webkitTransform = "rotate(" + deg + "deg)";
}

/**
 * 设置输入总量
 * @param  {number} total  输入总量
 */
function setInputTotal(total) {
    var strTotal = '';
    if(total > 99999999) {
        var n = parseInt(total / 100000000);
        strTotal =  ">" + n;
        skin.g('key').innerHTML = "亿字";
    } else if(total > 9999999) {
        var n = parseInt(total / 10000);
        strTotal =  ">" + n;
        skin.g('key').innerHTML = "万字";
    } else {
        if(total > 999999) {
            skin.g('input_sum').style.paddingRight = '20px';
            skin.g('input_sum').style.width = '178px';
        }
        strTotal = skin.addComma(total);
        skin.g('key').innerHTML = "字";
    }

    skin.g('totalInput').innerHTML = strTotal;
    refreshMedalInfo({key: 'inputTotal', val: total});
}

/**
 * 设置历史最快输入速度
 * @param  {number} record  历史最快输入速度
 */
function setInputRecord(record) {
    skin.g('maxInputed').innerHTML = record/* + '<span class="font24">/</span><span class="font18">min</span>'*/;
    skin.g('maxInput').innerHTML = record;
    skin.g('maxInputKey').innerHTML = record;
    setDashboard(record);
}
/**
 * 获取用户级别
 * @param  {number} score 用户积分
 * @return {number}       用户当前级别
 */
function getUserLevel(score) { 
    var k = 0;
    while (score > config.level[k]) { 
        k++;
    }
    return (k > 10) ? 10 : k;
}
/**
 * 设置用户级别
 * @param  {number} score 用户积分
 */
function setUserLevel(score) {
    skin.userLevel = getUserLevel(score);
    skin.g('levelNum').innerHTML = 'LV' + skin.userLevel;
    skin.g('levelIng').style.width = (score / config.level[skin.userLevel] * config.levelBarW) + 'px';
    skin.g('levelTitle').innerHTML = score + '/' + config.level[skin.userLevel];
}

/**
 * 获取用户输入成就
 * @param {number} inputTotal 用户输入总量
 * @return {object}       用户成就描述
 */
function getInputAchievement (inputTotal) { 
    var k = 0; 
    while (k < writeResult.length && inputTotal > writeResult[k].maxLen) { 
        k++;
    }
    k = (k >= writeResult.length) ? (writeResult.length - 1) : k;
    return writeResult[k];
}
/**
 * 设置用户输入成就
 * @param {number} inputTotal 用户输入总量
 */
function setInputAchievement(inputTotal) {
    var opts = getInputAchievement(inputTotal);  
    var html = '<span>' + opts.description + '</span>';  
    if (opts.keyword) {
        html += '<a href="#" id="openSearch" onmouseup="doSearch(this)" isbook="' + opts.isBook + '" keyword="' + opts.query + '" class="hand">' + opts.keyword + '</a>';
    }
    if (opts.endText) {
        html += opts.endText;
    }
    skin.g('tab_sum_value').innerHTML = skin.addComma(inputTotal);
    skin.g('writeResult').innerHTML = html;
}
/**
 * 搜索(成就关键词点击)
 * @param  {string} keyword 搜索关键字
 */
function doSearch (obj) {
    var keyword = obj.getAttribute('keyword');
    if (obj.getAttribute('isbook') == 'true') {
        keyword = '《' + keyword + '》';
    } 
    var openParam =  {
        needLogin: false,
        url: 'http://www.baidu.com/s?wd=' + encodeURIComponent(keyword) + '&tn=SE_baidupinyin'
    };
    skin.execOrder('openUrl', JSON.stringify(openParam));
}
/**
 * 处理勋章点亮数据
 * @param {object} medals 勋章列表
 */
function setMedals (medals) {
    skin.medalsStatu = {}; 
    for (var i = 0, iLen = medals.length; i < iLen; i++) {
        skin.medalsStatu[medals[i]] = 1;
    }
}
/**
 * 刷新勋章列表显示
 */
function buildMedal(li, medalName) {
    var medal = config.medals[medalName];
    li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
    li.setAttribute('medal', medalName);
    li.innerHTML = '<div class="medalmask rel"><p class="abs"></p></div>';
    li.onmouseover = function (e) {
        li.style.backgroundPosition = '0' + ' ' + (medal.bgIndex * (-43) + 'px');
        showMedalInfo(this, 1);
        skin.medalInfo.onmouseover = function () {
            li.style.backgroundPosition = '0' + ' ' + (medal.bgIndex * (-43) + 'px');
            skin.show(skin.medalInfo);
        };
        skin.medalInfo.onmouseout = function () {
            li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
            if (!skin.isHoverMedal) {
                skin.hide(skin.medalInfo);
            }
        };
    };
    li.onmouseout = function (e) {
        li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
        showMedalInfo(this, 0);
    };
    return li;
}
/**
 * 显示|隐藏勋章详情浮窗
 * @param  {object}  obj     li元素
 * @param  {number} isHover 是（1）否（0）点亮
 */
function showMedalInfo(obj, isHover) {
    skin.isHoverMedal = isHover;
    if (isHover) { 
        var num = parseInt(obj.getAttribute('num'));
        num = (num > skin.medalLineCount - 1) ? (num - skin.medalLineCount) : num;
        var left = obj.offsetLeft + config.medalInfoOf.left + (parseInt(obj.parentNode.style.left) || 0);
        if (num % 10  < 7) {
            skin.medalInfo.style.left = left + 'px';
            skin.removeClass(skin.medalInfo, 'left');
        } else {
            skin.medalInfo.style.left = left + 'px';
            skin.addClass(skin.medalInfo, 'left');
        }

        skin.medalInfo.style.top = (obj.offsetTop + config.medalInfoOf.top) + 'px';
        // 设置勋章详情浮窗
        setMedalInfo(obj.getAttribute('medal'));
        skin.show(skin.medalInfo);
    } else {
        skin.hide(skin.medalInfo);
    }
}
/**
 * 设置勋章详情
 */
function setMedalInfo (medalName) {
    var medal = config.medals[medalName]; 
    var html = '';
    skin.g('medalTitle').innerHTML = medal.title;
    
    html += '<p>' + medal.desc + '</p>';
    if (typeof medal['plan'] != 'undefined' && medal.plan.total < medal.plan.minVal && medal.statu == 0) {
        html += '<p>进度:<span class="plan">' + medal.plan.total + '/' + medal.plan.minVal + '</span>' + medal.plan.unit + '</p>';
    }
    if (typeof medal['fireOrder'] != 'undefined') {
        html = html.replace('<a>', '<a href="#" onclick="openPlugin(\'' + medal['fireOrder'] + '\')">');
        //html[html.length] = '<p class="go-finish"><span onclick="openPlugin(\'' + medal['fireOrder'] + '\')">去做任务</span></p>';
    }
    skin.g('medalText').innerHTML = html;
}
function openPlugin(openType) {    
    if (openType == 'setDefault') {
        skin.execOrder('setDefault');
    } else {
        skin.execOrder('openPlugin', openType);
    }
}
/**
 * 处理勋章显示
 * @param {object} medals 勋章列表
 */
function proccessMedals(medals) { 
    setMedals(medals);
    var k = 0;
    var li;
    skin.medalList.innerHTML = '';
    // 重新获取勋章列表的状态
    for (var m in config.medals) {
        // 创建顺序索引值
        config.medals[m]['mIndex'] = k;
        config.medals[m].statu = skin.medalsStatu[m] ? 1 : 0; 
        li = document.createElement('li');
        li.setAttribute('num', k+'');
        skin.medalList.appendChild(buildMedal(li, m));
        k++;
    }
    //自适应填充 medalList  update by xuxincheng
    // skin.medalList.style.width = (Math.ceil(k) * (config.medalW +  config.medalL)) + 'px';
    skin.medalLineCount = Math.ceil(k);
}

/**
 * 勋章列表滚动显示
 * @param  {number} direction 方向(1/-1)
 */
function scrollMedalsBox (direction) {
    skin.hide(skin.medalInfo);
    var w = config.medalScrollW;
    var items = skin.g('medalNav').getElementsByTagName('span');
    if (direction > 0) {
        //skin.medalList.className = 'prevPage_1';
        skin.medalList.style.left = '0';
        skin.removeClass(items[1], 'cur');
        skin.addClass(items[0], 'cur');
        skin.removeClass('medalNext', 'right-arrow-disabled');
        skin.addClass('medalPrev', 'left-arrow-disabled');
    } else {
        //skin.medalList.className = 'nextPage_1';
        skin.medalList.style.left = -w + 'px';
        skin.removeClass(items[0], 'cur');
        skin.addClass(items[1], 'cur');
        skin.removeClass('medalPrev', 'left-arrow-disabled');
        skin.addClass('medalNext', 'right-arrow-disabled');
    }
}

/**
 * 绑定滚轮事件
 * @param  {object} element    鼠标触发对象
 * @param  {function} scrollFunc 处理函数
 */
function proccessScrollEvent(element, scrollFunc) {
    skin.addEvent(element, 'mousewheel', function (e) {
        skin.stopEvent(e);
        var wheelDelta = skin.getWheelValue(e);
        scrollFunc(wheelDelta);
    });
}


/**
 * 
 * 礼品中心 左右滑动
 * @param direction -1 左箭头  1 右箭头
 * */

function slideGiftBox(direction) {

    var curClickTimer = new Date().getTime();
    if(curClickTimer - timer < 500) {   // 两次时间过短则不执行下一次
        timer = curClickTimer;          //重置全局时间戳 判断下一次
        return;
    }
    timer = curClickTimer;

    var ele = skin.g('gift_center_box');
    var style = ele.currentStyle ? ele.currentStyle : window.getComputedStyle(ele, null);
    var giftBoxLength = ele.getElementsByTagName('div').length;

    var pageLeftDistance = - parseInt(giftBoxLength) * config.giftLen;
    var curLeft = parseInt(style.left);
    if(direction == 1) {   // 向右滑动

        curLeft -= 608;
        if(curLeft <= pageLeftDistance) {
            return;
        }

        if(curLeft - 608 <= pageLeftDistance) {  // 下页箭头需要置灰

            skin.addClass('page_down','page-down-disabled');
            if(curLeft <= -608) {
                skin.removeClass('page_up','page-up-disabled');
            }

            skin.g('gift_center_box').style.left = curLeft + 'px';
        } else {
            if(curLeft <= -608) {
                skin.removeClass('page_up','page-up-disabled');
            }

            skin.g('gift_center_box').style.left = curLeft + 'px';
        }

    } else {
        if (curLeft >= 0) {
            skin.addClass('page_up','page-up-disabled');
            return;
        }
        if (curLeft + 608 >= 0) {
            skin.addClass('page_up','page-up-disabled');
        }
        curLeft += 608;
        skin.g('gift_center_box').style.left = curLeft + 'px';

        if(curLeft - 608 > pageLeftDistance) {
            skin.removeClass('page_down','page-down-disabled');

        }
    }
}


/**
 * 已登录用户--账号设置
 */
function proccessUserSetting() {
    skin.hide('userItems');
    skin.userItemBox = false;
    var userParam = {needLogin: false, url: config.userSettingUrl};
    skin.execOrder('openUrl', JSON.stringify(userParam)); 
}
/**
 * 已登录用户--退出
 */
function proccessLoginOut(){
    skin.hide('userItems');
    proccessLoginIme(false);
    skin.userItemBox = false;
    skin.execOrder('clickReport', 5);
}
/**
 * 已登录用户--显示用户设置
 */
function proccessUserItems() {
    if (skin.userItemBox) {
        skin.userItemBox = false;
        skin.hide('userItems');
    } else {   
        skin.userItemBox = true;     
        skin.show('userItems');
    }
}
/**
 * 处理未登录情况下提示相关事件
 */
function proccessUnloginMedal() {
    if (!skin.bindUnloginMedal) {
        skin.bindUnloginMedal = true;
        // 未登录
        // 这中间的代码已被删除了 by liangweibin
    }    
}
/**
 * 刷新-设置经验和金币（供客户端调用）
 * @param {object} data 对应信息
 */
function setExpCoin (data) {
    // 设置等级
    setUserLevel(data.exp);
    // 设置金币
    skin.g('coin').innerHTML = data.coin;
}
/**
 * 刷新--点亮某个勋章（供客户端调用）
 * @param {object} data 勋章信息
 */
function fireMedal (data) {
    config.medals[data.medal].statu = 1;
    var medal = config.medals[data.medal];
    var li = skin.medalList.getElementsByTagName('li')[medal.mIndex];
    buildMedal(li, data.medal);    
}

function showGiftInfo() {
    skin.show('succ_modal');
    skin.show('awardTips');
    // 重置按钮状态

    skin.g('toExchange').innerHTML = '确定兑换';
    skin.g('toExchange').style.background = '#3385ff';
    skin.g('msg').innerHTML = '';
    skin.g('gift_info_box').style.display = 'inline-block';
    skin.g('gift_exchange_info').style.display = 'none';
    skin.g('gift_exchange_error').style.display = 'none';
}

function showExchangeSucc() {
    skin.g('gift_info_box').style.display = 'none';
    skin.g('gift_exchange_info').style.display = 'inline-block';
    skin.g('gift_exchange_error').style.display = 'none';
}


function showExchangeError() {
    skin.show('succ_modal');
    skin.show('awardTips');
    skin.g('gift_info_box').style.display = 'none';
    skin.g('gift_exchange_info').style.display = 'none';
    skin.g('gift_exchange_error').style.display = 'inline-block';
}

/**
* 礼品中心回调函数
*
* */
function getGiftData(uid, bduss) {
    skin.g('gift_center_box').innerHTML = '';
    skin.show('giftLoading');
    var JSONP = document.createElement("script");
    JSONP.type="text/javascript";
    if (uid) {  // 用户已登录
        JSONP.src = "http://shurufa.baidu.com/shurufa/api/storerecommend?uid=" + uid +"&callback=jsonpFunc";
    } else {    // 用户未登录
        JSONP.src = "http://shurufa.baidu.com/shurufa/api/storerecommend?callback=jsonpFunc";
    }

    document.getElementsByTagName("body")[0].appendChild(JSONP);

    window.jsonpFunc = function (data) {
        skin.g('gift_center_box').style.left ='0px';
        skin.g('gift_center_box').innerHTML = '';

        var giftList = data['list'];
        var giftListLen = giftList.length;
        if (giftListLen == 0) { //显示
            skin.hide('giftLoading');
            skin.show('giftEmpty_tips');
            skin.hide('page_up');
            skin.hide('page_down');
            return;
        }

        skin.hide('giftLoading');
        skin.hide('giftEmpty_tips');

        // 初始化左右滑动箭头状态
        skin.addClass('page_up', 'page-up-disabled');
        if(giftListLen <= 3) {
            skin.hide('page_up');
            skin.hide('page_down');
            skin.addClass('page_down', 'page-down-disabled');
        } else {
            skin.show('page_up');
            skin.show('page_down');
            skin.removeClass('page_down', 'page-down-disabled');
        }
        
        var left = 0;

        // 显示礼品的详细信息   礼品名称  礼品详细描述  礼品价格
        for(var i in giftList) {
            var giftbox = document.createElement('div');
            giftbox.setAttribute('class','gift-box');
            giftbox.setAttribute('id','gift_box_'+i);
            giftbox.setAttribute('award_id', giftList[i]['id']);
            giftbox.style.background = 'url('+ giftList[i]['image_1']+')';
            giftbox.style.backgroundSize = 'cover';
            giftbox.style.left = left + 'px';

            var span1 = document.createElement('span');
            span1.innerHTML = giftList[i]['name'];
            span1.setAttribute('class','giftname');

            var span2 = document.createElement('span');
            span2.innerHTML = giftList[i]['description'];
            span2.setAttribute('class','description');


            var span3 = document.createElement('span');
            span3.innerHTML = giftList[i]['prices'];
            span3.setAttribute('class','price');

            giftbox.appendChild(span1);
            giftbox.appendChild(span2);
            giftbox.appendChild(span3);
            skin.g('gift_center_box').appendChild(giftbox);

            left += 202;
        }


        var giftObj = skin.getElementsClass('gift-box');

        exchangeGift(giftObj,uid,bduss);

    };

}

function exchangeGift(giftObj, uid, bduss) {
    if(!uid) {   //用户未登录直接
        for (var i in giftObj) {
            giftObj[i].style.cursor = 'default';
            var id = giftObj[i].getAttribute('id');
            skin.removeClass(id,'gift-box-hover');
        }
        return;
    }  else {
        for (var i in giftObj) {
            giftObj[i].style.cursor = 'pointer';
            var id = giftObj[i].getAttribute('id');
            skin.addClass(id,'gift-box-hover');
        }
    }

    for (var i in giftObj) {
        giftObj[i].onclick = (function (j) {
            return function () {   // 闭包处理内部函数快速执行
                // 点击礼品 数据上报
                skin.execOrder('clickReport', 15);

                var curGift = giftObj[j];
                var giftname = skin.getElementsClass('giftname')[j].innerHTML;
                var giftdescription = skin.getElementsClass('description')[j].innerHTML;
                var giftprice = skin.getElementsClass('price')[j].innerHTML;

                skin.g('giftname').innerHTML = giftname;
                skin.g('giftdes').innerHTML = giftdescription;
                skin.g('gift_coin').innerHTML = giftprice;

                var url = 'http://shurufa.baidu.com/shurufa/api/api_user_score_award';
                try {
                    baidu.ajax.request(url, {
                        method: 'POST',
                        data: 'action=scoreAward&id=' + curGift.getAttribute('award_id') + '&bduss=' + bduss,
                        timeout: 3000,
                        onsuccess: function (xhr, res) {
                            /*err_code:
                             成功：0
                             失败: 1礼品已经下架; 2金币不足; 3礼品不存在; 4没有登录
                             5兑换失败; 6已兑换; 7还未到兑换时间; 8已过兑换截止时间
                             9虚拟货币兑换，总兑换次数已用完
                             10虚拟货币兑换，单日可兑换次数已用完
                             11虚拟货币兑换，用户可兑换总次数已用完
                             12虚拟货币兑换，用户单日可兑换次数已用完
                             13特权皮肤、特权表情、虚拟货币激活码不存在
                             */
                            var res = JSON.parse(res);
                            if (res['err_code'] == '0'|| res['err_code'] == '6' || res['err_code'] == '7' || res['err_code'] == '8'||res['err_code'] == '9'||res['err_code'] == '10'||res['err_code'] == '11'||res['err_code'] == '12'||res['err_code'] == '13') {
                                if(res['err_code'] == '6') {   // 已兑换
                                    showGiftInfo();
                                    skin.g('msg').innerHTML = '每个礼品每天仅允许兑换1次，请明天再来吧';
                                    skin.g('toExchange').innerHTML = '已兑换';
                                    skin.g('toExchange').style.background = '#aeaeae';
                                } else {
                                    if(res['err_code'] == '0') {

                                        if(res['award_type'] == '0') {
                                            showGiftInfo();
                                            skin.g('toExchange').innerHTML = "立即换肤";
                                        } else if (res['award_type'] == '1'){
                                            showGiftInfo();
                                            skin.g('toExchange').innerHTML = "立即添加";
                                        } else {
                                            showGiftInfo();
                                        }
                                    } else {

                                        showGiftInfo();
                                        skin.g('toExchange').style.background = '#aeaeae';
                                        skin.g('msg').innerHTML = res['msg'];
                                    }

                                }

                            } else { //校验兑换失败  1/礼品下架  2/金币不足   3/礼品不存在    4/没有登录
                                if (res['err_code'] == '2') {  // 金币不足
                                    showExchangeError();
                                } else {
                                    showGiftInfo();
                                    skin.g('toExchange').style.background = '#aeaeae';
                                    skin.g('msg').innerHTML = res['msg'];
                                }

                            }

                        },
                        onfailure: function () {
                            showGiftInfo();
                            skin.g('toExchange').innerHTML = '知道啦';
                            //skin.g('toExchange').style.background = '#aeaeae';
                            skin.g('msg').innerHTML = "兑换失败，请检查网络情况并重试!";
                            skin.g('toExchange').onclick = function () {
                                hideModal();
                                skin.hide('awardTips');
                            }

                        },
                        ontimeout: function (xhr) {

                        }
                    });
                } catch (e) {}

                skin.g('toExchange').onclick = function () {
                    var url = 'http://shurufa.baidu.com/shurufa/api/api_user_score_award';
                    try {
                        baidu.ajax.request(url, {
                            method: 'POST',
                            data: 'action=doAward&id=' + curGift.getAttribute('award_id') + '&bduss=' + bduss,
                            timeout: 3000,
                            onsuccess: function (xhr, res) {
                                var res = JSON.parse(res);
                                if (res['err_code'] == '-1') { // 参数错误
                                    showGiftInfo();
                                    skin.g('msg').innerHTML = res['msg'];
                                    skin.g('toExchange').style.background = '#aeaeae';

                                } else if(res['err_code'] == '5') { // 兑换失败
                                    showGiftInfo();
                                    skin.g('msg').innerHTML = res['msg'];
                                    skin.g('toExchange').style.background = '#aeaeae';

                                } else if (res['err_code'] == '0'||res['err_code'] == '6'|| res['err_code'] == '7' ||res['err_code'] == '8'||res['err_code'] == '9'||res['err_code'] == '10'||res['err_code'] == '11'||res['err_code'] == '12' ||res['err_code'] == '13' ) {
                                    if(res['err_code'] == '0' ||res['err_code'] == '6'){
                                        if(res['err_code'] == '0') {  // 兑换成功   皮肤、表情、虚拟货币
                                            // 只要兑换成功  通知客户端刷新金币
                                            skin.execOrder('refreshCoin');
                                            if (parseInt(res['award_type']) == 0){
                                                //兑换特殊表情，执行：立即换肤操作
                                                var opts = {
                                                    type:'skin',
                                                    id: res['detail']['id']
                                                };

                                                skin.execOrder('getOtherGift', JSON.stringify(opts));
                                                hideModal();
                                                skin.hide('awardTips');

                                            } else if (parseInt(res['award_type']) == 1) {   // 表情

                                                var opts = {
                                                    type:'emotion',
                                                    id: res['detail']['id']
                                                };

                                                skin.execOrder('getOtherGift', JSON.stringify(opts));
                                                hideModal();
                                                skin.hide('awardTips');

                                            } else if (parseInt(res['award_type']) == 2) {
                                                var opts = res.virtual_award|| {};
                                                opts.id = res.id;
                                                opts.virtualCode = res.detail;
                                                skin.g('exchange_code').innerHTML = res.detail;
                                                showExchangeSucc();  // 兑换码窗口

                                                //兑换虚拟商品，执行： 未兑换过 弹出兑换码
                                                skin.g('copytoExchange').onclick = function () {
                                                    var text = skin.g('exchange_code').innerHTML;

                                                    var value = {needLogin: false, val: text};
                                                    skin.execOrder('copyToClipboard', JSON.stringify(value));

                                                    var urlParam = {needLogin: false, url: opts.link};
                                                    skin.execOrder('openUrl', JSON.stringify(urlParam));
                                                    skin.execOrder('clickReport', 17);
                                                    hideModal();
                                                    skin.hide('awardTips');
                                                };

                                            }

                                            // 数据上报
                                            skin.execOrder('clickReport', 16);

                                        }

                                    } else {  // 7、8、9、10、11、12、13  兑换不成功原因
                                        showGiftInfo();
                                        skin.g('toExchange').style.background = '#aeaeae';
                                        skin.g('msg').innerHTML = res['msg'];
                                    }

                                } else {   // 1、礼品已下架   3、礼品不存在   4、未登录
                                    showGiftInfo();
                                    skin.g('toExchange').style.background = '#aeaeae';
                                    skin.g('msg').innerHTML = res['msg'];
                                }

                            },
                            onfailure: function () {
                                showGiftInfo();
                                skin.g('msg').innerHTML = "请检查网络状态并重试!";

                            },
                            ontimeout: function (xhr) {

                            }
                        });
                    } catch (e) {}
                }


            };

        })(i);
    }
    
}

/**
 * 设置用户信息（供客户端调用）
 * @param {object} data 用户信息列表
 */

function setUserInfo (data) {
    processHeadMask(data.passport.login);
    if (data.passport.login) {
        skin.g('uName').innerHTML = data.passport.uname + '<div id="userBox" onclick="proccessUserItems();" class="userbox abs"><div id="userItems" class="user-items abs"><p onclick="proccessUserSetting()" id="userSetting">账号设置</p><p onclick="proccessLoginOut()" id="logout">退出</p></div></div>';
        // 设置头像
        setUserHead(data.passport.uid, data.passport.uname);   
        skin.removeClass('isLogined', 'unlogin');
        skin.hide('unloginMsg');
        skin.show('loginMsg');
        skin.hide('gift_login_box');
        skin.show('gift_center_info');
        skin.isLogin = true;

        skin.show('coin_title_word');

        // 处理礼品中心数据
        getGiftData(data.passport.uid, data.passport.loginBduss);


    } else {
        //testData('!');
        //用户未登录
        getGiftData();
        skin.hide('coin_title_word');

        skin.g('uName').innerHTML = '<a id="headLogin" class="loginbtn button">登录</a>';
        skin.g('headLogin').onclick = function () {
            proccessLoginIme(true);
            //getGiftData();
            skin.execOrder("clickReport", 3);
        };
        //礼品中心处登录
        skin.g('goLogin').onclick = function (e) {
            proccessLoginIme(true);
            // getGiftData();
            skin.execOrder('clickReport', 12);
        };
        // 取消个人中心头像处登录
        /*skin.g('headMask').onclick = function (e) {
            proccessLoginIme(true);
            getGiftData();
        };*/
        // 设置未登录头像
        skin.g("uHead").src = config.unloginHead;
        skin.addClass('isLogined', 'unlogin');
        skin.hide('loginMsg');
        skin.show('unloginMsg');
        skin.show('gift_login_box');
        skin.hide('gift_center_info');
        skin.isLogin = false;

        //showFullLoginTip();
        //skin.hide('full_tip_exchange');
    }
    // 设置等级
    setUserLevel(data.exp);
    // 设置金币
    skin.g('coin').innerHTML = data.coin;

    skin.g('medalnum').innerHTML = data.medals.length;
    skin.g('medalnum_title').innerHTML = data.medals.length;
    // 设置勋章
    proccessMedals(data.medals);
}
/**
 * 显示未登录medal遮罩图层（供客户端调用）
 */
function showTips() {
    // 绑定事件
    proccessUnloginMedal();
}
/**
 * 是否显示未登录medal遮罩图层（供客户端调用）
 */
function isNoTipsEcho(val) {
    if (!val){
        // 绑定事件
        proccessUnloginMedal();
    }
}
/**
 * 设置输入信息（供客户端调用）
 * @param  {object} data 用户近期输入信息数据
 */
function setInputData (data) {
    var drawData;
    skin.inputData = data;
    skin.inputData.dailyRecords = proccessInputData(data.dailyRecords);
    skin.recordsLen = skin.inputData.dailyRecords.length;
    // 天数处理成7的倍数
    if (skin.recordsLen >= 7 && skin.recordsLen % 7 > 0) {
        skin.recordsLen -= skin.recordsLen % 7;
        skin.inputData.dailyRecords = skin.inputData.dailyRecords.slice(0, skin.recordsLen);
    }
    if (skin.recordsLen <= 7) {
        drawData = skin.inputData.dailyRecords;
        skin.tablePageTotal = 1;
        skin.tablePageNum = 1;
        skin.addClass('prevDays', 'left-arrow-disabled');
        skin.addClass('nextDays', 'right-arrow-disabled');
    } else {
        skin.tableDays = skin.inputData.dailyRecords.length;
        skin.tablePageTotal = Math.ceil(skin.tableDays / 7);
        skin.tablePageNum = skin.tablePageTotal;
        drawData = skin.inputData.dailyRecords.slice(0, 7);
        skin.removeClass('prevDays', 'left-arrow-disabled');
    }
    // 绘制近期输入趋势图
    buildTable(skin.g('inputTableCanvas'), drawData, skin.inputData.maxDailySum);
    // 设置查看输入趋势图
    proccessChangeTable();
    // 输入总量
    setInputTotal(skin.inputData.inputTotal);
    // 历史输入最快速度
    setInputRecord(skin.inputData.maxSpeed);
    // 设置用户输入成就
    setInputAchievement(skin.inputData.inputTotal);
    // 若输入总量、历史速度皆为0，则显示一个tips
    if (!skin.inputData.inputTotal && !skin.inputData.maxSpeed) {
        setTimeout(function(){
            skin.show('tips00');
        }, 500);
    } else {
        skin.hide('tips00');
        setTimeout(function(){
            skin.hide('tips00');
        }, 501);
    }
}
/**
 * 刷新当日输入信息（供客户端调用）
 * @param  {object} data 最新的输入信息数据
 */
function refreshTodayInput(data) {
    // 更新用户输入数据--今天输入量|输入总量|历史输入最快速度
    skin.inputData.dailyRecords[0].total = data.inputToday;
    skin.inputData.inputTotal = data.inputTotal;
    skin.inputData.maxSpeed = data.maxSpeed;
    skin.inputData.maxDailySum = (skin.inputData.maxDailySum > data.inputToday) ? skin.inputData.maxDailySum : data.inputToday;

    if (skin.tablePageNum == 1) {
        // 重绘近期输入趋势图
        buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(0, 7), skin.inputData.maxDailySum);
    }    
    // 输入总量
    setInputTotal(skin.inputData.inputTotal);
    // 历史输入最快速度
    setInputRecord(skin.inputData.maxSpeed);
    // 设置用户输入成就
    setInputAchievement(skin.inputData.inputTotal);
    // 若输入总量、历史速度皆为0，则显示一个tips
    if (!skin.inputData.inputTotal && !skin.inputData.maxSpeed) {
        setTimeout(function(){
            skin.show('tips00');
        }, 500);
    } else {
        skin.hide('tips00');
        setTimeout(function(){
            skin.hide('tips00');
        }, 501);
    }
}
/**
 * 刷新表情进度信息（供客户端调用）
 * @param  {object} opts 刷新参数
 */
function refreshMedalInfo(opts) {
    var order = config.orderMap[opts.key];
    for (var i = 0, iLen = order.length; i < iLen; i++) {
        config.medals[order[i]].plan.total = opts.val;
    }
}
/**
 * 返回有效数据列表
 * @param  {object} list 28天输入数据列表
 * @return {object}      计算后的数据列表
 */
function proccessInputData(list) {
    var len = list.length;
    var count = Math.ceil(list.length / 7);
    var num = len % 7;
    var c = 0;
    var k = 0;
    for (var iLen = list.length - 1, i = iLen; i >= 0; i--) {        
        if (list[i].total > 0) {
            break;
        }
        k++;
    }
    if (k >= num) {
        c = num;
        c = c +  Math.floor((k - num) / 7) * 7;
        // 至少保留一个趋势图
        c = (c == len) ? len - 7 : c;
    }

    return  (c== 0) ? list : list.slice(0, len - c); 
}
/**
 * 设置查看近期输入趋势图
 */
function proccessChangeTable() {
    skin.g('prevDays').onclick = function () {
        if (skin.tablePageNum > 1) {
            skin.tablePageNum--;  
            var startIndex = (skin.tablePageTotal - skin.tablePageNum) * 7;             
            if (skin.tablePageNum == 1) {
                buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex), skin.inputData.maxDailySum);
            }  else {
                buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex, startIndex + 7), skin.inputData.maxDailySum);
            }   
        }  
        if (skin.tablePageNum == 1 || skin.tablePageTotal == 1) {
            skin.addClass(this, 'left-arrow-disabled');
        } else {
            skin.removeClass(this, 'left-arrow-disabled');
        }
        if (skin.tablePageTotal > 1) {
            skin.removeClass('nextDays', 'right-arrow-disabled');
        }
    };
    skin.g('nextDays').onclick = function () {  
        if (skin.tablePageNum < skin.tablePageTotal) {
            skin.removeClass(this, 'right-arrow-disabled');
            skin.tablePageNum++;
            var startIndex = (skin.tablePageTotal - skin.tablePageNum) * 7; 
            buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex, startIndex + 7), skin.inputData.maxDailySum);   
        }  
        if (skin.tablePageNum == skin.tablePageTotal) {
            skin.addClass(this, 'right-arrow-disabled');
        } else {
            skin.removeClass(this, 'right-arrow-disabled');
        }
        if (skin.tablePageTotal > 1) {
            skin.removeClass('prevDays', 'left-arrow-disabled');
        }
    }
}
/**
 * 设置用户头像
 * @param {string} uid 用户id
 * @param {string} uname 用户名称
 */
function setUserHead (uid, uname) {
    var url = 'http://ime.baidu.com/?act=lottery&k=getimg&t=geturl&uid=' + uid + '&uname=' + encodeURIComponent(uname);
    try {
        baidu.ajax.request(url + '&rnd=' + (+new Date()),{ 
            method: 'GET',
            data: '',       
            timeout: 3000,
            onsuccess:function (xhr, result) {
                skin.g("uHead").src = result;
            },
            onfailure: function () {
            },
            ontimeout: function (xhr) {
            }
        });
    } catch (e) {}
}
/**
 * 设置头像可点击登录
 * @param {Boolean} isLogin [description]
 */
function processHeadMask(isLogin) {
    var logined = isLogin ? '1' : '0';
    skin.g('headMask').setAttribute('logined', isLogin);
    /*if (logined == '0') {
        skin.g('headMask').onclick = function () {
            skin.execOrder('openLoginWnd1');
        }        
    } else {
        // 改版取消链接
        /!*skin.g('headMask').onclick = function () {
            var userParam = {needLogin: false, url: config.userSettingUrl};
            skin.execOrder('openUrl', JSON.stringify(userParam)); 
        }*!/
    }*/
}
/**
 * 登录|退出
 * @param  {Boolean} val 是否为登录操作
 */
function proccessLoginIme(val) {
    if (val) {
        skin.execOrder('openLoginWnd');
    } else {
        skin.execOrder('logout');
    }    
}
/**
 * 上传本地图片
 * @param  {object} opts 上传所需参数
 */
function uploadLocalImage (opts) {
    if (typeof opts == 'string') {
        opts = JSON.parse(opts);
    }
    var _type = replaceReg(opts.type);
    if (typeof window['proccessUpload' +_type] == 'function') {
        window['proccessUpload' + _type](opts);
    }
}
/**
 * 获取分享地址
 * @return {string} 分享地址
 */
function getShareURL() {
    var url = config.share.url;
    var items = config.share.opts;
    var k = 1;
    for (var c in items) {
        if (k == 1) {
            k = '?';
        } else {
            k = '&';
        }
        url = url + k + c + '=' + items[c];
    }
    return url;
}
/**
 * 设置分享地址
 * @param {string} key   参数名称
 * @param {string|number|bool} value 参数值
 */
function  setShareURL(key, value) {
    config.share.opts[key] = value;
}
/**
 * 绑定分享事件
 */
function initShareButton() {
    var items = config.share.items;
    var opts;
    for (var s in items) {        
        skin.g(items[s]).onclick = function () { 
            skin.hide('shareBox');   
            if ('weixin' == this.id) {
                opts = {type: this.id, url: config.share.weixinSign};
            } else {
                opts = {type: this.id};
            }      
            window.setTimeout(function (){
				skin.execOrder('share', JSON.stringify(opts)); 
			}, 30);           
        }
    }
}
/**
 * 处理上传提示(供客户端调用)
 * @param  {bool} result 上传结果
 */
function didShare(result) {
    if (result == "true") {
        showUpload(false);
    } else {
        showUpload(false);
        skin.show("errUpload");
    }
}
function showUpload(show) {
    if (show) {
        skin.show("doUpload");  
        load.loading();
    } else {
        skin.hide("doUpload");
        load.clearTimer();
    }
}
/**
 * 关闭上传错误提示弹窗
 */
function closeErrDialog() {
    skin.hide("errUpload");
}
/**
 * 执行分享(供客户端调用)
 * @param  {object} opts 分享内容(图片地址,分享类型)
 */
function doShare(opts) {    
    setShareURL('pic', opts.imgSrc);
    setShareURL('to', opts.shareType);
    var shareOpts = {needLogin: false, url: getShareURL()};
    skin.execOrder('openUrl', JSON.stringify(shareOpts)); 
}
/**
 * 把字符串转换为首字母大写形式
 * @param  {string} keyword 是字符串
 * @return {string}         新字符串
 */
function replaceReg(keyword) {
    var reg = /\b(\w)|\s(\w)/g;
    return keyword.replace(reg, function (m) { return m.toUpperCase(); });
}

function showFullLoginTip () {
    // todo: 读取标记判断是否曾经弹过
    if (skin.execOrder('isNoLoginTips') * 1) return;
    skin.show('full_tip_login');
    skin.g('full_tip_login_close_1').onclick = skin.g('full_tip_login_close_2').onclick = function () {
        hideFullLoginTip();
    };
    skin.g('full_tip_login_login').onclick = function () {
        skin.execOrder('openLoginWnd1');
        hideFullLoginTip();
    };
}
function hideFullLoginTip () {
    skin.execOrder('setNoLoginTips');
    skin.hide('full_tip_login');
}

function showFullExchangeTip () {
    if (skin.execOrder('isNoTips') * 1) return;
    skin.show('full_tip_exchange');
    skin.g('full_tip_exchange_close').onclick = function () {
        hideFullExchangeTip();
    };
    skin.g('full_tip_exchange_exchange1').onclick = skin.g('full_tip_exchange_exchange2').onclick = function () {
        skin.getAward();
        hideFullExchangeTip();
    };
}

function hideFullExchangeTip () {
    skin.execOrder('setNoTips');
    skin.execOrder('setNoLoginTips');
    skin.hide('full_tip_exchange');
}


var load = {
    totle: 12,
    width: 32,
    count: 0,
    loadTimer: null,
    obj: skin.g("load"),
    clearTimer: function () {
        if (this.loadTimer) {
            window.clearTimeout(this.loadTimer);
            this.loadTimer = null;
        }
    },
    loading: function () {
        ++ this.count;
        if (this.count == this.totle) {
            this.count = 0;
        }
        this.obj.style.backgroundPosition = (-1 * this.count * 32) + "px 0";               
        window.setTimeout(function () {
            load.loading();
        }, 80);
    }
};

/*测试数据*/
function testData(str) {
    skin.g('test_data').innerHTML += '<br />' + str;
}

function showBox(id) {
    skin.g('succ_modal').style.display = 'block';  //遮罩层显示
    skin.g(id).style.display = 'block';
}

function hideBox(id) {
    skin.g(id).style.display = 'none';
    skin.g('succ_modal').style.display = 'none';
}

// 显示对应的tab 
function showTab(id) {
    showBox('succ_box');
    skin.g(id).style.display = 'inline-block';

    var tabarr = ['tab_sum','tab_fast','tab_medal'];
    for (var i in tabarr) {
        if(tabarr[i] != id) {
            skin.g(tabarr[i]).style.display = 'none';
        }
    }

}

function showModal() {
    skin.g('succ_modal').style.display = 'block';
}
function hideModal() {
    skin.g('succ_modal').style.display = 'none';
}
skin.boxMouseOver = function (name) {
    var imgId = name + 'Img';
    var wordId = name + 'Word';
    skin.g(imgId).style.backgroundPosition = "-30px 0";
    skin.g(wordId).style.color = "#3385ff";
};

skin.boxMouseOut = function (name) {
    var imgId = name + 'Img';
    var wordId = name + 'Word';
    skin.g(imgId).style.backgroundPosition = "0 0";
    skin.g(wordId).style.color = "#828f9d";

};

skin.showTabTitle = function (id) {
    skin.g(id).style.backgroundColor = "#3385ff";
    skin.g(id).style.color = "#ffffff";
    var arr = ['tab_title_sum','tab_title_fast','tab_title_medal'];
    for (var i in arr) {
        if(arr[i] != id) {
            skin.g(arr[i]).style.backgroundColor = "#f7f7f7";
            skin.g(arr[i]).style.color = "#333333";
        }
    }
};

skin.showTabBox = function (title_id,tab_id) {
    skin.showTabTitle(title_id);
    showTab(tab_id);
};

skin.coinview = function () {
    var coinviewParam = {needLogin: false, url: config.coinLink};
    skin.execOrder('openUrl', JSON.stringify(coinviewParam));
    skin.execOrder('clickReport', 14);
};

/**
 * 清空金币信息（用户退出的时候 供客户端调用）
 */

function exitResetCoin() {
    setHtml('coin_sum', 0);             // 设置 总金币数
    setHtml('today_coin_sum', 0);  // 今日已获得金币数

    setHtml('todayInputWordCount', 0);     // 今日已输入数据
    setHtml('todayInputWordCoin', '+' + 0);       // 对应金币

    setHtml('todayEmotionCount', 0);         // 今日已输入表情
    setHtml('todayEmotionCoin', '+' + 0);           // 对应金币

    setHtml('todayEmotionWordCount', 0); // 今日已输入颜文字
    setHtml('todayEmotionWordCoin', '+' + 0);       // 对应金币

    setHtml('todayUseToolCount', 0);         // 今日已使用工具
    setHtml('todayUseToolCoin', '+' + 0);           // 对应金币

    setHtml('useSkinCount', 0);                   // 已使用皮肤
    setHtml('useSkinCoin', '+' + 0);


    setHtml('addDictCount', 0);                   // 已添加词库
    setHtml('addDictCoin', '+' + 0);                     // 对应金币


    setHtml('addEmotionPackageCount', 0);   // 已添加几个表情包
    setHtml('addEmotionPackageCoin', '+' + 0);

    setHtml('todayActive', '+' + 0);                      // 用户日活跃

    setHtml('hasLoginCount', '+' + 0);                // 已登录输入法
    setHtml('firstLogin', '+' + 0);                   // 首次登录输入法

    setHtml('firstSetDefaultInput', '+' + 0);   // 首次设置为默认输入法
    setHtml('firstLockDefaultInput', '+' + 0);   // 首次设置为默认输入法

    // 首页登陆后金币显示
    setHtml('currCoinSum', 0);
    setHtml('canUseCoin', 0);

}

/**
 * 设置金币信息（供客户端调用）
 * @param  {object} data 设置用户金币数据
 */

function setCoinData(data) {
    setHtml('coin_sum', data.coinSum);             // 设置 总金币数
    //setHtml('coin_sum', 100000000);
    setHtml('today_coin_sum', data.todayCoinSum);  // 今日已获得金币数

    setHtml('todayInputWordCount', data.todayInputWordCount);     // 今日已输入数据
    setHtml('todayInputWordCoin', '+' + data.todayInputWordCoin);       // 对应金币

    setHtml('todayEmotionCount', data.todayEmotionCount);         // 今日已输入表情
    setHtml('todayEmotionCoin', '+' + data.todayEmotionCoin);           // 对应金币

    setHtml('todayEmotionWordCount', data.todayEmotionWordCount); // 今日已输入颜文字
    setHtml('todayEmotionWordCoin', '+' + data.todayEmotionWordCoin);       // 对应金币

    setHtml('todayUseToolCount', data.todayUseToolCount);         // 今日已使用工具
    setHtml('todayUseToolCoin', '+' + data.todayUseToolCoin);           // 对应金币

    setHtml('useSkinCount', data.useSkinCount);                   // 已使用皮肤
    if (data.useSkinCount == 0) {
        setHtml('useSkinCoin', '<a id="goFinishSkin" class="goFinish">去完成</a>');
    } else {
        setHtml('useSkinCoin','+' + data.useSkinCoin);                      // 对应金币
    }


    setHtml('addDictCount', data.addDictCount);                   // 已添加词库
    if (data.addDictCount == 0) {
        setHtml('addDictCoin', '<a id="goFinishDict" class="goFinish">去完成</a>');                     // 对应金币
    } else {
        setHtml('addDictCoin', '+' + data.addDictCoin);
    }


    setHtml('addEmotionPackageCount', data.addEmotionPackageCount);   // 已添加几个表情包
    if (data.addEmotionPackageCount == 0) {
        setHtml('addEmotionPackageCoin', '<a id="goFinishEmotion" class="goFinish">去完成</a>');
    } else {
        setHtml('addEmotionPackageCoin', '+' + data.addEmotionPackageCoin);     // 对应金币
    }

    setHtml('todayActive', '+' + data.todayActive);                      // 用户日活跃
    setHtml('hasLoginCount', '+' + data.loginCountCoin);                // 已登录输入法

    if (data.firstLoginCoin == -1) {
        setHtml('firstLogin', '已完成');
    } else {
        setHtml('firstLogin', '+' + data.firstLoginCoin);   // 首次登录输入法
    }


    if (data.firstSetDefaultInput == -1) {
        setHtml('firstSetDefaultInput', '已完成');
    } else {
        setHtml('firstSetDefaultInput', '+' + data.firstSetDefaultInput);   // 首次设置为默认输入法
    }

    if (data.firstLockDefaultInput == -1) {
        setHtml('firstLockDefaultInput', '已完成');
    } else {
        setHtml('firstLockDefaultInput', '+' + data.firstLockDefaultInput);   // 首次设置为默认输入法
    }


    // 首页登陆后金币显示
    setHtml('currCoinSum', data.coinSum);
    /*setHtml('currCoinSum', 1000000);
    setHtml('canUseCoin', 1000000);*/
    setHtml('canUseCoin', data.coinAvail);

    skin.g('goFinishSkin').onclick = function () {
        var goFinishSkin = {needLogin: false, url: config.skinLink};
        skin.execOrder('openUrl', JSON.stringify(goFinishSkin));
        skin.execOrder('clickReport', 18);
    };

    skin.g('goFinishEmotion').onclick = function () {
        skin.openEmotionCenter();
        skin.execOrder('clickReport', 19);
    };

    skin.g('goFinishDict').onclick = function () {
        var goFinishDict = {needLogin: false, url: config.dictLink};
        skin.execOrder('openUrl', JSON.stringify(goFinishDict));
        skin.execOrder('clickReport', 20);
    };




}

/**
 *  定位到输入成就（供客户端调用）
 */
function setInputSuc(){
    skin.g('input_sum').click();
}

/**
 * 定位到金币获得明细供客户端调用）
 */
function setCoinDetail(){
    skin.g('coin_title_word').click();
}

function setHtml(id,value) {
    skin.g(id).innerHTML = value;
}



skin.openSkinBox = function () {
    skin.execOrder('openSkinBox');
};

skin.openEmotionCenter = function () {
    skin.execOrder('openEmotionCenter');
};

skin.openUseDict = function () {
    skin.execOrder('openUserDict');
};


skin.g('ok').onclick = function () {
    skin.hide('succ_modal');
    skin.hide('awardTips');
};

/*debug区域 解决XP下3个像素的偏移*/
if (navigator.userAgent.indexOf("Windows NT 5.1") > -1) { // 5.1XP
    skin.g('hrline').style.top = "78px";
} else {
    skin.g('hrline').style.top = "81px";
}


