/*
	common.js
	放置公用函数
	文档载入时公用部分
*/
$(document).ready(function(){
	//对页面中的外部链接进行样式加载
	var siteUrl = ["www.woosuko.com","woosuko.com","www.sacn.kr","sacn.kr","oknow.woosuko.com","oknow.sacn.kr"];
	
	$("a[href^='http://']").addClass('url');
	
	for (var i in siteUrl) {
		$("a[href^=http://" + siteUrl[i] + "]").removeClass('url').addClass('outUrl');
	}
	
	//顶部菜单
	$('#loginedExpand').click(function(){
		$(this).addClass('hidden');
		$('#logined').removeClass('hidden');
	});
	$('#logined').click(function(){
		$(this).addClass('hidden');
		$('#loginedExpand').removeClass('hidden');
	});
	//投票按钮hover
	$('.diggBtn').hover(
		function(){
			$(this).addClass("diggBtnHover"); 
		},
		function(){
			$(this).removeClass("diggBtnHover"); 
	});
});
/*IE 6 修正*/
$(window).load(function(){
	var bv = browserVersion();
	if ($.browser.msie && bv == '6.0') {
		var elems = ['header','wrapper','footer']; 
		widthForIe(elems);
		var searchBarElem = 'searchbar';
		widthForIe(searchBarElem,600,360,2);
		var wrapperElem = 'wrapper';
		heightForIe(wrapperElem);
	}
});
$(window).resize(function(){				  
	var bv = browserVersion();
	if ($.browser.msie && bv == '6.0') {
		var elems = ['header','wrapper','footer']; 
		widthForIe(elems);
		var searchBarElem = 'searchbar';
		widthForIe(searchBarElem,600,360,2);
	}
});
//min-width max-width min-height保证IE 6兼容
function widthForIe(elem,maxVal,minVal,mode) {
	if (elem === null || typeof elem == 'undefined' || elem == '') return;
	if (maxVal === null || typeof maxVal == 'undefined' || maxVal == '') maxVal = 1600;
	if (minVal === null || typeof minVal == 'undefined' || minVal == '') minVal = 740;
	if (mode === null || typeof mode == 'undefined' || mode == '') mode = 1;
	var obj;
	var width;
	if (mode == 1) {
		width = $(window).width();
		if (elem.constructor == Array && elem.length > 0) {
		for (var i = 0; i < elem.length; i++)　{
			obj = $('#' + elem[i]);
			if (width > maxVal)
				obj.width(maxVal);
			else 
				obj.width(width);
			if (width < minVal) 
				obj.width(minVal);
			else
				obj.width(width);
		}
		} else {
			width = obj.width();
			if (width > maxVal) 
				obj.width(maxVal);  
			else 
				obj.width(width);
			if (width < minVal) 
				obj.width(minVal);
			else
				obj.width(width);
		}
	} else if(mode == 2) {
		obj = $('#' + elem);
		width = obj.width();
		if (elem.constructor == Array) {
			return;
		} else {
			if (width > maxVal) 
				obj.width(maxVal);  
			else
				obj.width(width);
			if (width < minVal) 
				obj.width(minVal);
			else
				obj.width(width);
		}
	} else {
		return;
	}
}
function heightForIe(elem,minVal) {
	if (elem === null || typeof elem == 'undefined' || elem == '') return;
	if (minVal === null || typeof minVal == 'undefined' || minVal == '') minVal = 380;
	var obj = $('#' + elem);
	var height = obj.height();
	
	if (elem.constructor == String) {
		if (height < minVal) 
			obj.height(minVal);  
		else 
			obj.height(height);
	} else {
		return;
	}
}
//判断浏览器版本号
function browserVersion() {
	var version;
	var userAgent = navigator.userAgent.toLowerCase();
	if (window.ActiveXObject)
		version = userAgent.match(/msie ([\d.]+)/)[1];
	else if (document.getBoxObjectFor)
		version = userAgent.match(/firefox\/([\d.]+)/)[1];
	else if (window.MessageEvent && !document.getBoxObjectFor)
		version = userAgent.match(/chrome\/([\d.]+)/)[1];
	else if (window.opera)
		version.opera = userAgent.match(/opera.([\d.]+)/)[1];
	else if (window.openDatabase)
		version = userAgent.match(/version\/([\d.]+)/)[1];
	return version;
}
//回到页面顶部
function backTotop(elem) {
		if (elem === null || elem == '' || elem == 'undefined') return;
		var obj = $('#' + elem);
		obj.hide();
		$(window).scroll(function(){
			var x = $(document).scrollLeft();
			var y = $(document).scrollTop();
			obj.fadeIn('slow');
			if (x == 0 && y == 0) {
				obj.fadeOut('slow');
			}
		});
		obj.click(function(){
			bttScroll();
			return false;
		});
}
function bttScroll() {
	var x = $(document).scrollLeft();
	var y = $(document).scrollTop();
	window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));
	if (x > 0 || y > 0) {
		setTimeout(function(){bttScroll();},10);
	}
}
//去左空格
function ltrim(s){ 
	return s.replace( /^\s*/, ""); 
} 	
//去右空格 
function rtrim(s){ 
	return s.replace( /\s*$/, "").replace(/&nbsp;/ig,""); 
} 
//去左右空格
function trim(s){ 
	return rtrim(ltrim(s)); 
} 
/*
	判断单双字符 计算字符数目
*/
function charCount(str) {
	var word;
	var count = 0;
	if(!str) return "0";
	for (var i=0;i<str.length;i++){
		word = str.substr(i,1);
		if(word.charCodeAt(0)>255){
			count = count + 2;
		}
		else {
			count ++;
		}
	}
	return count;
}
//表单检测
var formTester = {
	validBox:"validateTips",
	checkLength:function(obj,maxVal,minVal){
		var value = trim(obj.val());
		var msg;
		var regExp = /^[\u2E80-\u9FFF\uac00-\ud7ff\uf900-\ufaffa-zA-Z0-9-_.\s+!,]+$/i.test(value);
		var length = charCount(value);
		if(length == 0) {
			this.checkRequired(obj);
			return false;
		} else if (length > maxVal) {
			msg = "内容过长，超过" + maxVal + "字符";
			this.updateMsg(obj,msg);
			return false;
		} else if (length < minVal) {
			msg = "内容过短，少于" + minVal + "字符";
			this.updateMsg(obj,msg);
			return false;
		} else if (!regExp) {
			msg = "内容包含非法字符";
			this.updateMsg(obj,msg);
			return false;
		} else {
			obj.next("." + formTester.validBox).remove();
			return true;
		}		
	},
	checkRequired:function(obj){
		var name = obj.prev('label').text() || obj.parent().prev().find('label').text();
		var msg = "请填写" + name;
		this.updateMsg(obj,msg);
	},
	checkCode:function(obj,num){
		var value = trim(obj.val());
		var msg;
		var regExp = /^[0-9a-z]+$/i.test(value);
		if (value.length == 0) {
			this.checkRequired(obj);
			return false;
		} else if (value.length != num) {
			msg = "验证码为" + num + "位";
			this.updateMsg(obj,msg);
			return false;
		} else if (!regExp) {
			msg = "验证码为英文或者数字";
			this.updateMsg(obj,msg);
			return false;
		} else{
			return true;	
		}
	},
	checkEmail:function(obj,minVal) {
		var value = trim(obj.val());
		var msg;
		var regExp = /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(value);
		if (value.length == 0) {
			this.checkRequired(obj);
			return false;
		} else if (value.length < minVal || !regExp) {
			msg = "邮件地址不正确 e.g:admin@woosuko.com";
			this.updateMsg(obj,msg);
			return false;
		} else {
			return true;
		}
	},
	checkMCE:function(obj,maxVal,minVal){
		var msg;
		var value = trim(obj.val());
		var regExp = /<\/?.+?>/g;
		value = value.replace(regExp,"");
		var length = charCount(value);
		if (length == 0) {
			msg = "请填写内容";
			this.mceMsg(obj,msg);
			return false;
		} else if (length < minVal) {
			msg = "内容过短，少于" + minVal + "字符";
			this.mceMsg(obj,msg);
			return false;
		} else if (length > maxVal) {
			msg = "内容过长，超过" + maxVal + "字符";
			this.mceMsg(obj,msg);
			return false;
		} else {
			return true;
		}
	},
	checkTAG:function(obj){
		
	},
	checkURL:function(obj){
		var msg;
		var value = trim(obj.val());
		var arr = [];
		arr = value.split(/\n/);
		var regExp = /^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/;
		for (var i in arr) {
			if(!this.checkRegExp(regExp,arr[i])){
				msg = "地址不正确";
				break;
			}
		}
		if (msg) {
			this.updateMsg(obj,msg);
			return false;
		} else {
			return true;
		}
	},
	checkRegExp:function(regexp,value){
		return regexp.test(value);
	},
	updateMsg:function(obj,msg){
		var tipsBox = '<span class="' + this.validBox + '">' + msg + '<\/span>';
		obj.next("." + this.validBox).remove();
		obj.addClass('ui-state-error').after(tipsBox);
	},
	mceMsg:function(obj,msg){
		var postTips = $('.postTips');
		var tipsBox = '<span class="' + this.validBox + '">' + msg + '<\/span>';
		postTips.prev("." + this.validBox).remove();
		obj.next().after(tipsBox);
	}
};
/*
	图片圆角化
	
	实现功能
	结合了jquery,对任意图片进行圆角化，兼容IE\FF\Opera\Safari\Chrome
	
	过程描述
	1.获取元素中的IMG元素
	2.对IMG元素进行替换，转换为CANVAS
	3.创建canvas进行遮罩层的绘制
	
	存在的问题
	<del>1.IE 8 在不开启兼容模式下无法实现并且不显示图片=>强制客户端开启IE7兼容模式<=解决</del>
	<del>2.Chrome&&Safari不能获取到img的真实高度<=解决：不使用document ready而使用window load这样在图片加载之后才执行</del>
	3.动画效果中IE的圆角框变形
	<del>4.Opera隐藏元素高度为原值<=解决</del>
	
	最佳解决方案
	excanvas.js实现clip函数
	
	关于源代码
	来自校内的CVI_CORNERS函数
	有关VML的模拟实现有待研究
	
	Hitigon 2009-8-6
*/
var drawImageCorners = {
	
	addVMLNamespace: function() {
		var e=["shape","shapetype","group","background","path","formulas","handles","fill","stroke","shadow","textbox","textpath","imagedata","line","polyline","curve","roundrect","oval","rect","arc","image"];
		var s=document.createStyleSheet(); 
		for(var i=0; i<e.length; i++) {s.addRule("v\\:"+e[i],"behavior: url(#default#VML);");}
		document.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML"); 		
	},
	
	init : function(options){
		options = {
			srcImg:options.srcImg || null,
			width:options.width || 50,
			height:options.height || 50,
			xRadius:options.xRadius || 6,
			yRadius:options.yRadius || 6
		};
		if (options.srcImg === null) return;
		try {
			var imgs = options.srcImg;
			var id = imgs.attr('id');
			var src = imgs.attr('src');
			var alt = imgs.attr('alt');
			var width = (imgs.attr('width') > options.width) ? options.width : imgs.attr('width');
			var height = (imgs.attr('height') > options.height) ? options.height : imgs.attr('height');
			var display = imgs.css('display');
			var float = imgs.css('float');
			if ($.browser.msie && !window.opera) {
				if(document.namespaces.v==null) {
					this.addVMLNamespace();
				}
				display = (display=='block')?'block':'inline-block';
				var canvas = document.createElement(['<var style="zoom:1;overflow:hidden;display:' + display + ';width:' + width + 'px;height:' + height + 'px;padding:0;">'].join(''));
				display = (float == 'left' || float == 'right') ? 'inline' : display;
				canvas.options = options;
				canvas.id = id;
				canvas.alt = alt;
				canvas.source = src;
				canvas.width = width;
				canvas.height = height;
				imgs.replaceWith(canvas);
				drawImageCorners.create(canvas,options);
			} else if (navigator.userAgent.indexOf("Chrome") != -1 || $.browser.safari) {
				var canvas = document.createElement("div");
				var radius;
				if (options.xRadius == options.yRadius) radius = options.xRadius;
				canvas.id = id;
				canvas.source = src;
				canvas.style.width = width + 'px';//bug
				canvas.style.height = height + 'px';
				canvas.style.background = "url(" + src + ") no-repeat center center";
				canvas.style.WebkitBorderRadius = radius + 'px';
				imgs.replaceWith(canvas);
			} else {
				var canvas = document.createElement('canvas');	
				if (canvas.getContext) {
					canvas.options = options;
					canvas.id = id;
					canvas.alt = alt;
					canvas.source = src;
					canvas.width = width;
					canvas.height = height;
					imgs.replaceWith(canvas);
					drawImageCorners.create(canvas,options);
				}
			}
		} catch(e) {
			return false;
		}
	},
	
	create : function(canvas, options) {
		try {
			var xRadius = options['xRadius'];
			var yRadius = options['yRadius'];
			xRadius = Math.min(parseInt(canvas.width/2),xRadius);
			yRadius = Math.min(parseInt(canvas.height/2),yRadius);
			if(xRadius > 0 && yRadius == 0) yRadius = Math.min(parseInt(canvas.width/2),xRadius);
			if(yRadius > 0 && xRadius == 0) xRadius = Math.min(parseInt(canvas.height/2),yRadius);
			canvas.options['xRadius'] = xRadius;
			canvas.options['yRadius'] = yRadius; 
			if ($.browser.msie && !window.opera) {
				if(canvas.tagName.toUpperCase() == "VAR") {
						var path = "m 0," + yRadius; var display = canvas.display;
						path += " l 0," + (canvas.height-yRadius) + " qy " + xRadius + "," + canvas.height;
						path += " l " + (canvas.width-xRadius) + "," + canvas.height + " qx " + canvas.width + "," + (canvas.height-yRadius);
						path += " l " + canvas.width + "," + yRadius + " qy " + (canvas.width-xRadius) + ",0";
						path += " l " + xRadius + ",0 qx 0," + yRadius;
						path += " x e";
						canvas.innerHTML = '<v:shape stroked="f" strokecolor="#0000FF" filled="t" fillcolor="#ffffff" coordorigin="0,0" coordsize="' + canvas.width + ',' + canvas.height + '" path="' + path + '" style="zoom:1;margin:-1px 0 0 -1px;padding: 0;display:' + display + ';width:' + canvas.width + 'px;height:' + canvas.height + 'px;"><v:fill src="' + canvas.source + '" ' + 'origin="0.5,0.5" position="0.5,0.5" style="" type="tile" /></v:shape>';
				}
			} else {
				if (canvas.getContext) {
					var context = canvas.getContext('2d');
					var img = new Image();
					img.onload = function() {
						canvas.height = img.height > canvas.height ? canvas.height : img.height;
						canvas.width = img.width > canvas.width ? canvas.width : img.width;
						//开始绘图-顺时针
						context.clearRect(0,0,canvas.width,canvas.height);
						context.save();
						context.beginPath();
						context.moveTo(xRadius,0);
						context.lineTo(canvas.width-xRadius,0);
						context.quadraticCurveTo(canvas.width,0,canvas.width,yRadius);
						context.lineTo(canvas.width,canvas.height-yRadius);
						context.quadraticCurveTo(canvas.width,canvas.height,canvas.width-xRadius,canvas.height);
						context.lineTo(xRadius,canvas.height);
						context.quadraticCurveTo(0,canvas.height,0,canvas.height-yRadius);
						context.lineTo(0,yRadius);
						context.quadraticCurveTo(0,0,xRadius,0);
						context.closePath();
						//遮罩clip函数
						context.clip();
						context.fillStyle = 'rgba(0,0,0,0)';
						context.fillRect(0,0,canvas.width,canvas.height);
						if (img.height > img.width) {
							context.drawImage(img,0,parseInt((img.height - canvas.height)/2),canvas.width,canvas.height,0,0,canvas.width,canvas.height);
						} else {
							context.drawImage(img,0,0,img.width,img.height,0,0,img.width,img.height);
						}
						context.restore();
						
					};
					img.src = canvas.source;
				}	
			}

		} catch(e) {
			return false;
		}
	}
};
//对所需元素绘制图片圆角
function selectCornerElems (elem,width,height) {
	var elem = elem || null;
	var width = width || 50;
	var height = height || 50;
	if (elem === null) return;
	var length = elem.length;
	for (var i = 0; i < length; i++) {
		drawImageCorners.init({
			srcImg:$('#' + elem.get(i).id),
			width:width,
			height:height
		});
	}
}
