gbutil.js 13.4 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
/* ---------------------------------------------------------------------- */
/*   辅助方法:控制台Log信息
/* ---------------------------------------------------------------------- */
jQuery.gblog=function(a){if(window.console){console.log(a);}else{}};
jQuery.gberror=function(a){if(window.console){console.error(a);}else{}};

/* ---------------------------------------------------------------------- */
/*   辅助方法:重定向到gbtags.com
/* ---------------------------------------------------------------------- */
function redirectDomain(){
	if (document.domain =='gbin1.com') 
		this.location = "http://www.gbtags.com" + this.location.pathname + this.location.search;
	else if (document.domain =='www.gbin1.com') 
		this.location = "http://www.gbtags.com" + this.location.pathname + this.location.search;
}
redirectDomain();

/* ---------------------------------------------------------------------- */
/*   辅助方法:Redirect to 用户向导
/* ---------------------------------------------------------------------- */
function initwizard(){
	var url = window.location.href;
	

	if(global_onlineuser.uid!==0){
		if(global_onlineuser.avatar!==''){
			if(url.indexOf('gbwizard.htm')>0){
				window.location.href= global_contextPath + '/dashboard.htm';
			}
		}else if(!(url.indexOf('logout.htm')>0||url.indexOf('gbwizard.htm')>0||url.indexOf('vericode.htm')>0)){
			
				window.location.href= global_contextPath + '/gbwizard.htm';
			
		}
	}
	
}
initwizard();

/* ---------------------------------------------------------------------- */
/*   辅助方法:过滤处理HTML标签相关符号
/* ---------------------------------------------------------------------- */
function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}

/* ---------------------------------------------------------------------- */
/*   辅助方法:DWR统一出错信息
/* ---------------------------------------------------------------------- */
function handleThisCallsErrors(errorString, exception) { 
   var dwrmsg = new GBMessage({text:'网站无法完成请求,请刷新重试',id:'dwrmsgid'});
   dwrmsg.show();
   $.gberror('内部错误:' + errorString);
} 
dwr.engine.setErrorHandler(handleThisCallsErrors);

/* ---------------------------------------------------------------------- */
/*   辅助方法:系统信息/警告/错误提示
/* ---------------------------------------------------------------------- */
var GBMessage = function(o){
	this.id = o.id?o.id:'gbmessage';
	this.type = o.type?o.type:'warning';
	this.text = o.text?o.text:'系统提示';
	this.layout = o.layout?o.layout:'topCenter';
	this.speed = o.speed?o.speed:200;
	this.easing = o.easing?o.easing:'swing';
	this.timeout = o.timeout?o.timeout:1500;
};

GBMessage.prototype = {
	show: function(){
	  noty({
	    id: this.id,
	  	layout: this.layout,
	  	type: this.type,
	  	text: this.text,
	  	timeout: this.timetou,
		animation: {
	        open: {height: 'toggle'},
	        close: {height: 'toggle'},
	        easing: this.easing,
	        speed: this.speed
		}
	  });
	},
	close: function(){
		if(this.id){
			$.noty.close(this.id);
		}
	},
	closeall: function(){
		$.noty.closeAll();
	},
	closequeue: function(){
		$.noty.clearQueue();
	}
};

/* ---------------------------------------------------------------------- */
/*   辅助方法:删除数组元素 http://ejohn.org/blog/javascript-array-remove/
/* ---------------------------------------------------------------------- */

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

/* ---------------------------------------------------------------------- */
/*   辅助方法:用户封账号
/* ---------------------------------------------------------------------- */
$(function(){ 
	var url = window.location.href;
	if(global_onlineuser.uid&&(global_onlineuser.deleted===1)){
	   var banusermsg = new GBMessage({text:'您的账号违反本站使用规定,已被永久封闭,如果有任何异议,请联系管理员',id:'banusermsgid',timeout:5000,layout:'top',type:'information'});
	   banusermsg.show();
	   setTimeout(function(){window.location.href = global_contextPath + '/logout.htm';}, 6000);
	}
	
	if(global_onlineuser.uid&&(global_onlineuser.deleted===-1)&&url.indexOf('dashboard.htm')>0){
	   var mailvalidationmsg = new GBMessage({text:'您的电子邮件尚未验证 | 无法获取验证邮件?  <a target="_blank" href="' + global_contextPath + '/verihelp.htm" style="color:#222;">@请点击这里 </a> | 关闭提示',id:'banusermsgid',timeout:5000,layout:'top',type:'information'});
	   mailvalidationmsg.show();
	}
	
});

/* ---------------------------------------------------------------------- */
/*   辅助方法:用户邮件验证
/* ---------------------------------------------------------------------- */
$(function(){ 
	if(typeof global_vericode !=='undefined'&&global_vericode.length){
		identityService.saveMailVericode(global_vericode, {
			callback:function(data) {
				if(data>0){
					$('#vericode_result').html('<i class="glyphicon glyphicon-ok"></i>  已成功验证电子邮件,3秒后转向...');
				
					if(global_onlineuser.uid>0){
						setTimeout(function(){window.location.href= global_contextPath + '/reloaduser.htm?url=dashboard.htm';}, 3000);
					}else{
						setTimeout(function(){window.location.href= global_contextPath + '/syslogin.htm';}, 3000);
					}
				}
			}
		});
	}
});

/* ---------------------------------------------------------------------- 
 *   辅助方法:侦测IE版本 
 *	if ( ie < 8 ) {
 *	    // do your stuff, for instance:
 *	}
 *
 * ---------------------------------------------------------------------- */

var detect_ie = (function () {
    var undef, v = 3, div = document.createElement('div');

    while (
        div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
        div.getElementsByTagName('i')[0]
    );

    return v > 4 ? v : undef;
}());

function handleIEVersion() { 
   if(detect_ie < 8){
	   var iemsg = new GBMessage({text:'最低IE版本要求<span style="color:red;font-family:Arial;font-weight:bold;">IE8</span>,或使用Firefox,Chrome,Safari',id:'iemsg'});
	   iemsg.show();
	   $.gberror('浏览器版本过低,最低版本要求Internet explore 8');
	   window.location.href= global_contextPath + '/networks/update-browser.html';
   }
} 

handleIEVersion();

/* ---------------------------------------------------------------------- */
/*	back to up
/* ---------------------------------------------------------------------- */
$(function(){
	/* if footer not existed*/
	if($("#footer").length>0){
		$('body').append('<div id="backtotop" class="showme"><div class="bttbg"></div></div>');
		initGoToTop();
	}
});

function initGoToTop() {

		var orig_scroll_height = jQuery("#footer").position().top - jQuery(window).height()-200;
		
		// fade in #top_button
		jQuery(function () {
			jQuery(window).scroll(function () {
				//console.log(jQuery(this).scrollTop());
				if (jQuery(this).scrollTop() > 100) {
					jQuery('#backtotop').addClass('showme');
				} else {
					jQuery('#backtotop').removeClass('showme');
				}
			});
	
			// scroll body to 0px on click
			jQuery('#backtotop').click(function () {
				jQuery('body,html').animate({
					scrollTop: 0
				},  400);
				return false;
			});
		});
				
		if (jQuery(window).scrollTop() == 0) {
			jQuery('#backtotop').removeClass('showme');
		}else{
			jQuery('#backtotop').addClass('showme');
		}
}

/*
 * 显示日期
 */		
function displaydate(date){
		var mnow = moment(),
			mdate = moment(date);

	if(mnow.diff(mdate, 'days')>=1){
		return mdate.format("YYYY年MM月D日 HH:mm:ss");
	}else{
		return mdate.fromNow();
	}
}

/*
 * 获取URL中的顶级域名
 */	
function fetch_domain_of_url(url) {
  var    a      = document.createElement('a');
         a.href = url;
  return a.hostname;
}

/*
 * 获取字符串中的所有URL地址
 */	
function findUrls( text )
{
    var source = (text || '').toString();
    var urlArray = [];
    var url;
    var matchArray;

    // Regular expression to find FTP, HTTP(S) and email URLs.
    var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

    // Iterate through any URLs in the text.
    while( (matchArray = regexToken.exec( source )) !== null )
    {
        var token = matchArray[0];
        urlArray.push( token );
    }

    return urlArray;
}

$(function(){
	$('.gbeditor').summernote({
	  height: 250,
	  toolbar: [
	    ['style', ['style']], // no style button
	    ['style', ['bold', 'italic', 'underline', 'clear']],
	    ['para', ['ul', 'ol', 'paragraph']],
	    ['insert', ['picture', 'link']], 
	    ['table', ['table']],
	    ['help', ['help']]
	  ],
	  lang: 'zh-CN'
	});
	
	$('#liveclassstartdate').datetimepicker({
		format: 'mm/dd/yyyy hh:ii', 
		language: 'zh-CN',
		startDate: moment().add('hours', 24).toDate(),
		minuteStep: 30
	});
	
	$('#editliveclassfrm #liveclassstartdate').datetimepicker({
		format: 'mm/dd/yyyy hh:ii', 
		language: 'zh-CN',
		startDate: moment().toDate(),
		minuteStep: 30
	});
	
	$('#timerange').selectpicker({
		'selectedText': '1小时'
    });
    
	$('#editliveclassfrm #timerange').selectpicker({
		'selectedText': '1小时'
    });
});

//Handlebar helper
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' 需要两个参数");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' 使用了不存在的比较符号 "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Handlebars.registerHelper("math", function(lvalue, operator, rvalue, options) {
    lvalue = parseFloat(lvalue);
    rvalue = parseFloat(rvalue);
        
    return {
        "+": lvalue + rvalue,
        "-": lvalue - rvalue,
        "*": lvalue * rvalue,
        "/": lvalue / rvalue,
        "%": lvalue % rvalue,
        "%%": Math.floor((lvalue / rvalue)*100)
    }[operator];
});

var rendered = Handlebars.compile(
    '{{#each values}}' + 
    'i={{@index}}: ' +
    'i+1 = {{math @index "+" 1}}, ' + 
    'i-0.5 = {{math @index "+" "-0.5"}}, ' + 
    'i/2 = {{math @index "*" 2}}, ' + 
    'i%2 = {{math @index "%" 2}}, ' + 
    'i*i = {{math @index "*" @index}}\n' +
    '{{/each}}'
)({
    values : [ 'a', 'b', 'c', 'd', 'e' ]
});

Handlebars.registerHelper('fromNow', function(creationdate) {
	var creationdate = moment(creationdate),
		now = moment();
	if(now.diff(creationdate, 'days')>=1){
		return creationdate.calendar(); 
	}else{
		return creationdate.fromNow();
	}
});

//模板辅助方法:生成标签列表
Handlebars.registerHelper('tagList', function(object) {
	var usertagidlist = object.usertagids.split(','),
		taglist = object.tags.split(','),
		usertagdarenlist = object.usertagdaren.split(','),
		functionflaglist = object.usertagfunctionflag.split(','),
		tagsstr = '<p class="taglist">',
		tmpavatar = object.avatar!==''?object.avatar:'avatar.jpg',
		selftagflag = 0;
	
	/* 添加标示来判断自己的标签 */	
	if(object.uid==global_onlineuser.uid){
		selftagflag = 1;
	}					
	
	for(var a=0;a<taglist.length;a++){
		if(taglist[a]!==null&&taglist[a]!==''){
			if(functionflaglist[a]!='1'){
				tagsstr += 
				'<a class="btn btn-default btn-xs" target="_blank" href="' + global_contextPath + '/tag/usertag/' + usertagidlist[a] + '.htm">' +
				'<span class="avatar">' +
					'<img src="' + global_contextPath + '/networks/avatars/30x30' + tmpavatar + '" />' +
				'</span>' +
					taglist[a] +
				'</a>'; 
			}
		}
	}
	tagsstr += '<p class="clearfix"></p></p>';
	return tagsstr;
});

/*
 * 判断当前用户是否是讲师
 */
Handlebars.registerHelper('ifIsLiveClassTeacher', function(val, options) {
	if(val === global_onlineuser.uid){
		return options.fn(this);
	}else{
		return options.inverse(this);
	}
});

/*
 * 判断当前用户是否是讲师
 */
Handlebars.registerHelper('addPrettyPrintClass', function(s) {
	return s.replace(/\<pre\>/g,'<pre class="prettyprint linenums">');
});


/*
 * 日期转化
 */
Handlebars.registerHelper('gbdate', function(date) {
		var mnow = moment(),
			mdate = moment(date);

	if(mnow.diff(mdate, 'days')>=1){
		return mdate.format("YYYY年MM月D日");
	}else{
		return mdate.fromNow();
	}
});

Handlebars.registerHelper('abs', function(number) {

	return Math.abs(number);

});