var r=require("./r.js");
/**
 * Created by pc on 2015/3/24.
 */
//判断是否是整数
function checkNumber(str,flg){//flg用于判断是否是正整数
    var patternT = /^[1-9]\d{0,5}$/g;
    if(flg) patternT = /^[0-9]\d{0,5}$/g;
    var result = new RegExp(patternT);
    return result.test(str);
}

//过滤字段，需要的字段取出来
function filterFields(data,fields){
        var obj={};
        fields.forEach(function(e1){
             obj[e1]= data[e1];
        });
    return obj;
}


//用于返回错误信息
function replyError(rh,callback,status,msg){
    var reStr={};
    reStr.msg = msg||'MROBOT服务器加载数据错误';
    reStr.status=-1;
    rh.statusCode = status||500;

    rh.setHeader('Content-Type', 'application/json; charset=UTF-8');
    rh.setHeader('Cache-Control', 'no-cache');
    rh.setBody(JSON.stringify(reStr));
    callback(null, rh);
}


/**
 * 预加载时把content的内容里面的img进行src2处理
 * @param content 包括html标签的内容
 */
function loadImgSrc2(content) {
    content = content.replace(/<img[^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {//匹配得到<img xxx/>整个对象
        match = match.replace("src", "src2");
        match = match.replace("/>", " src=http://www1.pconline.com.cn/wap/2013/cms/img/best_loading.png />");
        return match;
    });
    return content;
}


Array.prototype.unique = function() {
    var res = [], hash = {};
    for(var i=0, elem; (elem = this[i]) != null; i++)  {
        if (!hash[elem])
        {
            res.push(elem);
            hash[elem] = true;
        }
    }
    return res;
};


function  get404Page(fs,hbs,req,rh,callback){
    var template = hbs.compile(fs.readFileSync('./static/404.html').toString());
    var html = template({});
    rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
    rh.setBody(html);
    callback(null,rh);
}
function isEmptyObject(obj){
    for(var n in obj){return false}
    return true;
}


function filterORG(stringToSearch) {
    var arrayToSearch=[91,49]
    for (s = 0; s < arrayToSearch.length; s++) {
        thisEntry = arrayToSearch[s].toString();
        if (thisEntry == stringToSearch) {
            return true;
        }
    }
    return false;
}

exports.checkNumber=checkNumber;
exports.filterFields=filterFields;
exports.replyError=replyError;
exports.loadImgSrc2=loadImgSrc2;
exports.get404Page=get404Page;
exports.isEmptyObject=isEmptyObject;
exports.filterORG=filterORG;



