var hbs = require('handlebars');

//注册一个比较大小的Helper,判断v1是否大于v2
hbs.registerHelper("compare",function(v1,v2,options){
	if(v1>v2){
		return options.fn(this);
	}else{
		return options.inverse(this);
	}
});
//注册一个字母大小写转换
hbs.registerHelper("helper_toLowerCase",function(str,options){
	if(str == null){
		return '';
	}
	return str.toLowerCase();
});
//注册一个比较大小的Helper,判断v1是否等于v2
hbs.registerHelper("equal",function(v1,v2,options){
	if(v1==v2){
		return options.fn(this);
	}else{
		return options.inverse(this);
	}
});

hbs.registerHelper('json', function(context) {
	return JSON.stringify(context);
});

hbs.registerHelper("moreCompare",function(v1,v2,v3,v4,options){
	if(v1>v2&&v3>v4){
		//满足添加继续执行
		return options.fn(this);
	}else{
		//不满足条件执行{{else}}部分
		return options.inverse(this);
	}
});

 
 /**
 * 是否包含
 * @param {Object} target
 * @param {Object} collections
 * @param {Object} options
 */ 
hbs.registerHelper("isContain", function(target, collections, options) {
	if (!target || !collections || Object.prototype.toString.call(collections) !== '[object Array]') {
		return '';
	}
	var size = collections.length;
	for (var i = 0; i < size; i++) {
		if (collections[i] == target)
			return options.fn(this);
	}
	return options.inverse(this);
});

hbs.registerHelper("eachIndex", function(array, options) {

	var i;
	var len;
	var result = '';
	var index = 0;
	var count = 1;
	var last = false;	
	try{
		for (index = i = 0, len = array.length; i < len; index = ++i) {
			var value = array[index];
			if(index == len-1) {
				last = true;
			}
			result += options.fn({
				item: value,
				index: index,
				count: index+1,
				last: last
			});
		}

	}catch (e) {}
	return result;
});

hbs.registerHelper("replaceStr",function(s1,s2,s3){
	try{
		return (s1==null?"":s1).replace(s2,s3);
	}catch (e) {
		return "";
	}
});

hbs.registerHelper("cutString",function(str,length){
   try{
		if (str == null) {
        	return "";
        }else {
        	return str.substring(0,length);
        }
	}catch(e){
		return str;
	}
});

hbs.registerHelper("cutCnString", function (str, len, hasDot) {
    try {
        var newLength = 0;
        var newStr = "";
        var chineseRegex = /[^\x00-\xff]/g;
        var singleChar = "";
        var strLength = str.replace(chineseRegex, "**").length;
        for (var i = 0; i < strLength; i++) {
            singleChar = str.charAt(i).toString();
            if (singleChar.match(chineseRegex) != null) {
                newLength += 2;
            }
            else {
                newLength++;
            }
            if (newLength > len) {
                break;
            }
            newStr += singleChar;
        }

        if (hasDot && strLength > len) {
            newStr += "...";
        }
        return newStr;
    } catch (e) {
        return newStr;
    }
});

hbs.registerHelper("subString",function(valueStr,begin,end){
    try{
        if (valueStr == null) {
            return "";
        }else {
            return valueStr.substring(begin,end);
        }
    }catch(e){
        return valueStr;
    }
});

hbs.registerHelper("photoPath",function(target,size){
	try{
		if(!target){
			return "http://www1.pcauto.com.cn/2010/price/img/slt/" + size +".jpg";
		}
		var pos = target.lastIndexOf(".");
		return target.substring(0,pos)+"_"+size+target.substring(pos,target.length);
	}catch (e) {
		return "";
	}
});

hbs.registerHelper("getList", function(array,pur) {
	try{
		if(array instanceof Array){
			return array[pur];
		}
	}catch (e) {
		return "";
	}
});
/**
 *  0-video.jsp；1-album.jsp；2-topic.jsp
 * 	获取静态路径
 */
hbs.registerHelper("getTypeNameStatic", function(type,id) {
	try{
	    switch (type) {
	        case 0:
	            return "video-" + id + ".html";
	        case 1:
	            return "album-" + id + ".html";
	        case 2:
	            return "topic-" + id + ".html";
	        default:
	            return "";
	    }
	}catch (e) {
		return "";
	}
});

hbs.registerHelper("sgTitle", function(obj) {
	try{
		var name = "";
		if(obj != null) {
			name = obj.name;
			if(name != null) {
				var reg=new RegExp("[a-zA-Z0-9]+"); 
				if(reg.test(name)){
					return name;
				}
			}
			var brand = obj.brand;
			if(brand != null) {
				return brand.name + name;
			}
		}
		return name;
	}catch (e) {
		return "";
	}
});


 /**
 * 便利map，map格式为map<key,list>
 */
hbs.registerHelper('eachMap', function(map, id, options) {
  	try{
	  	var i;
	    var len;
	    var result = '';
	    var index;
	    var array = map[id];
	    for (index = i = 0, len = array.length; i < len; index = ++i) {
	      result += options.fn(array[i]);
	    }
    }catch (e) {}
    return result;
});
/**
 * 便利map，map格式为map<key,Map>
 */
hbs.registerHelper('helper_eachMapMap', function(map, id, options) {
  	try{
  		var i = 0;
	    var result = '';
	    var mapObj = map[id];
	    for (var key in mapObj) {
	  	  result += options.fn({
	      	key: key,
	      	value: mapObj[key],
	      	index: i,
	      	first: (i==0)
	      });
	  	  i++;
	    }
    }catch (e) {}
    return result;
});

/**
 * 通过key获取map里面的Map，map格式为map<key,Map>
 */
hbs.registerHelper('helper_getMap', function(map, id, options) {
  	try{
	    var mapObj = map[id];
	    return options.fn(mapObj);
    }catch (e) {}
    return options.inverse(this);
});

/**
 * 把值设置进指定对象的属性内 配合BaseJson使用的话可以充当JSP中的<c:set>标签
 */
hbs.registerHelper("setValue", function(target, key) {
	if(!target || !key){
		console.error('Handlerbars Helper "setValue" can not access invalid "target" or "key"');
	}
	try {
		var expression = "";
		for (var i = 2; i < arguments.length - 1; i++) {
			expression += arguments[i];
		}
		target[key] = eval(expression);
	} catch (e) {
		throw new Error(e.message.replace('Error:','')+'\nHandlerbars Helper "setValue" can not set key:'+key);
	}
});


/**
去掉空白
**/
hbs.registerHelper('helper_trim', function(target) {
	try{
		return target.replace(/(^\s*)|(\s*$)/g, "");  
	}catch(e){
		return "";
	}
});


/**
小数位格式化,保留的位数：n
**/
hbs.registerHelper('helper_formatNumber', function(number, n, options) {
	try{
		return number.toFixed(n);
	}catch(e){
		return number;
	}
});

/**
*截取日期
*/
hbs.registerHelper('helper_todate', function(date,options) {
	try{
		
		var time = new Date(date);
		var month = time.getMonth()+1;
		var day = time.getDate();
		if(month < 10){
			month = '0'+month;
		}
		if(day < 10){
			day = '0'+day;
		}
		var str = month+'-'+day;
		return str;
	}catch(e){
		return date;
	}
});
/**
*日期格式化
*/
hbs.registerHelper('helper_dateformat', function(date, options) {
	try{
		var str = new Date(Date.parse(date.replace(/-/g,"/")));
		var year = str.getFullYear();
		var month = str.getMonth()+1;
		var day = str.getDate();
		var str1 = year+'年'+month+'月'+day+'日';
		return str1;
	}catch(e){
		return date;
	}
});



















/**
 * xps1的helper内容
 */
hbs.registerHelper('if_eq', function(v1, v2, options) {
    if (v1 == v2) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

hbs.registerHelper('if_noteq', function(v1, v2, options) {
    if (v1 != v2) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});
hbs.registerHelper('if_Sedeq', function(v1, v2,v3,v4,options) {
    if (v1 < v2 && v3 == v4) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});
hbs.registerHelper('if_gt', function(v1, v2, options) {
    if (v2 > v1) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

/*
 lt 小于
 */
hbs.registerHelper('if_lt', function(v1, v2, options) {
    if (v2 < v1) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

hbs.registerHelper('if_Alleq', function(v1, v2,v3,v4,options) {
    if (v1 == v2 && v3 == v4) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});


//把对象转化为json字符串,用于html里加备注_HTML里面的内容
hbs.registerHelper("objToStr",function(v1,option){
    return JSON.stringify(v1);
});


Date.prototype.Format = function(fmt){ //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}


/**
 * v1是毫妙数，v2为格式类型
 */
hbs.registerHelper('formatTime', function(v1, v2,v3, options) {
    var dateT=new Date(v1);
    var nowDate=new Date();
    if(v3&&nowDate.getFullYear()!=dateT.getFullYear()){//不是同一年
        //v2="yy-MM-dd hh:mm";
        v2=v3;
    }
    return dateT.Format(v2);
});