﻿var utils = (function() {
	return {
		//选项卡
		tab: function(topObject, botObject, Event) {
			var $a = $(topObject).find("a");
			$a.eq(0).addClass("focus");
			$(botObject).eq(0).show();
			$a.on(Event, function() {
				$(this).addClass("focus").siblings().removeClass("focus");
				var index = $(this).index();
				$(botObject).stop(true,true).eq(index).fadeIn().siblings(botObject).hide();
				if ($(topObject).find(".followTab").length > 0) {
					var width = $(this).width();
					$(topObject).find(".followTab").stop().animate({
						'left': index * width + 'px'
					}, 300);
				}
			});
		},
		//水平选项卡切换
		scrollTab: function(topTab, botTab) {
			var lens = $(topTab).children("p").find("a").length;
			$(botTab).children().width(lens * 100 + "%");
			$(botTab).children().children().width(100 / lens + "%");

			$(topTab).children("p").find("a").click(function() {
				var index = $(topTab).children("p").find("a").index(this);
				$(topTab).children("p").find("a").removeClass("focus");
				$(topTab).children("p").find("a").eq(index).addClass("focus");

				$(botTab).children().animate({
					marginLeft: -index * 100 + "%"
				});
				return false;
			});
		},
		//自动选项卡切换
		autoTab: function(topObject, botObject) {
			var $a = $(topObject).find("a");

			var timer = null;
			var num = 0;
			$(botObject).eq(0).show();

			$a.hover(function() {
				clearInterval(timer);
				num = $(this).index();
				tabChange();
			}, function() {
				autoPlay();
			});

			function tabChange() {
				$a.eq(num).addClass("focus").siblings().removeClass("focus");
				$(botObject).eq(num).fadeIn().siblings(botObject).hide();
			}

			function autoPlay() {
				timer = setInterval(function() {
					num++;
					if (num >= $a.length) num = 0;
					tabChange();
				}, 3000);
			}

			autoPlay();
		},
		//经过下拉
		dropDown: function(hoverObj, dropObj) {
			$(hoverObj).each(function() {
				var $this = $(this);
				var theMenu = $this.find($(dropObj));
				var tarHeight = theMenu.height();
				theMenu.css({
					height: 0
				});
				$this.hover(
					function() {
						theMenu.stop().show().animate({
							height: tarHeight
						}, 300);
					},
					function() {
						theMenu.stop().animate({
							height: 0
						}, 300, function() {
							$(this).css({
								display: "none"
							});
						});
					}
				);
			});
		},
		//模似select
		select: function(selectTop, selectBot) {
			$(selectTop).parent().each(function(i) {
				$(this).css('z-index', -(i) + 100);
			});

			$(selectTop).click(function(event) {
				event.stopPropagation();
				$(this).siblings(selectBot).slideToggle(300);
				$(this).toggleClass("focus");
			});
			$(selectBot).find("li").click(function(event) {
				event.stopPropagation();
				$(this).parent(selectBot).siblings(selectTop).find("p").text($(this).text());
				$(this).parent(selectBot).slideUp(300);
				$(this).parent(selectBot).siblings(selectTop).removeClass("focus");

			});
			$('html,body').click(function(event) {
				if ($(event.target).closest(selectTop).length == 0) {
					$(selectBot).slideUp(300);
					$(selectTop).removeClass("focus");
				}
			});
		},

		//金钱格式化
		moneyFormat: function(s, n) {
			n = n > 0 && n <= 20 ? n : 2;
			s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
			var l = s.split(".")[0].split("").reverse(),
				r = s.split(".")[1];
			t = "";
			for (index = 0; index < l.length; index++) {
				t += l[index] + ((index + 1) % 3 == 0 && (index + 1) != l.length ? "," : "");
			}
			return t.split("").reverse().join("") + "." + r;
		},

		//创建元素标签
		creElement: function(ele) {
			return document.createElement(ele);
		},

		//文件扩展名
		extension: function(fileName) {
			var result = fileName.replace(/.+\./, "").toUpperCase();
			return result;
		},

		//判断指定名称的复选框是否被选中
		chkCheck: function(chname) {
			var obj = $("[name='" + chname + "']");
			var isCheck = false;
			for (var i = 0; i < obj.length; i++) {
				if (obj[i].checked == true) {
					isCheck = true;
					break;
				}
			}
			return isCheck;
		},
		//复选框反选
		checkboxAll: function(chname) {
			$("[name='" + chname + "']").each(function() {
				$(this).attr("checked", true);
			});
		},
		//复选框全选
		inverSelect: function(chname) {
			$("[name='" + chname + "']").each(function() {
				if ($(this).attr("checked")) {
					$(this).attr("checked", false);
				} else {
					$(this).attr("checked", true);
				}
			});
		},
		selects: function(chname) {
			$("#" + all_id).click(function() {
				if ($(this).attr("checked")) {
					this.checkboxAll(chname);
				} else {
					this.clearSelect(chname);
				}
			});
		},
		//取消全选或反选
		clearSelect: function(chname) {
			$("[name='" + chname + "']").each(function() {
				$(this).attr("checked", false);
			});
		},
		//取消事件的默认行为
		preventDefault: function(event) {
			if (event.preventDefault) {
				event.preventDefault();
			} else {
				event.returnValue = false;
			}
		},
		//获取焦点
		getFocus: function(obj) {
			obj.on('click', function() {
				$(this).find('input').focus();
			});
		},
		//获取控件的值
		getValue: function(controlID, controltype) {
			var objValue = "";
			switch (controltype) {
				case 'text': //文本输入框
					objValue = $.trim($("#" + controlID + "").attr("value")); //取值去左右空格
					break;
				case 'radio': //单选框
					objValue = $("input[name='" + controlID + "']:checked").attr("value");
					break;
				case 'select': //下拉列表
					objValue = $("#" + controlID + "").attr("value");
					break;
				case 'checkbox': //多选框
					$("input[name='" + controlID + "']:checked").each(function() {
						objValue += $(this).val() + ",";
					});
					break;
				default:
					break;
			}
			return objValue;
		},
		//z-index 层级递减或递加
		zIndex: function(obj, n) {
			return $(obj).each(function(index) {
				if (n > 0) {
					$(this).css("z-index", +(index) + 100);
				} else {
					$(this).css("z-index", -(index) + 100);
				}
			});
		},
		//英文日期格式
		enDate: function(date) {
			return new Date(date).toDateString();
		},
		//手机号码隐藏四位
		telphone: function(number) {
			return number.replace(/\d{4}(?=\d{4}$)/, '****');
		},
		//获取真实图片的宽度和高度
		getImgSize: function(url, callback) { //url图片地址 callback回调函数里要传宽度和高度的参数
			var img = new Image();
			img.src = url;
			// 如果图片被缓存，则直接返回缓存数据
			if (img.complete) {
				callback(img.width, img.height);
			} else {
				// 完全加载完毕的事件
				img.onload = function() {
					callback(img.width, img.height);
				}
			}
		},
		//中英文混合文字截取
		interceptStr: function(text, length) {
			if (text.replace(/[\u4e00-\u9fa5]/g).length <= length) {
				return text;
			} else {
				var _length = 0;
				var outputText = '';
				for (var i = 0; i < text.length; i++) {
					if (/[\u4e00-\u9fa5]/.test(text[i])) {
						_length += 2;
					} else {
						_length += 1;
					};
					if (_length > length) {
						break;
					} else {
						outputText += text[i];
					};
				};
				return outputText;
			};
		},
		//滚动下拉头部下拉
		topScroll: function(obj) {
			var currentScrollPosition = $(window).scrollTop();
			if ($(window).scrollTop() > getHeaderHeight) {
				$('body').addClass('fixed').css('padding-top', getHeaderHeight);
				$(obj).css('top', 0);
				if (currentScrollPosition < (getHeaderHeight + 20)) {
					$(obj).css('top', '-' + (getHeaderHeight) + 'px');
				}
				lastScrollPosition = currentScrollPosition;
			} else {
				$('body').removeClass('fixed').css('padding-top', 0);
			}
		},
		//图片居中裁切
		VMiddleImg: function(obj) {
			return obj.each(function() {
				var $this = $(this);
				var objHeight = $this.height(); //图片高度
				var objWidth = $this.width(); //图片宽度
				var parentHeight = $this.parent().height(); //图片父容器高度
				var parentWidth = $this.parent().width(); //图片父容器宽度
				var ratio = objHeight / objWidth;
				if (objHeight > parentHeight && objWidth > parentWidth) {
					if (objHeight > objWidth) { //赋值宽高
						$this.width(parentWidth);
						$this.height(parentWidth * ratio);
					} else {
						$this.height(parentHeight);
						$this.width(parentHeight / ratio);
					}
					objHeight = $this.height(); //重新获取宽高
					objWidth = $this.width();
					if (objHeight > objWidth) {
						$this.css("top", (parentHeight - objHeight) / 2);
						//定义top属性
					} else {
						//定义left属性
						$this.css("left", (parentWidth - objWidth) / 2);
					}
				} else {
					if (objWidth > parentWidth) {
						$this.css("left", (parentWidth - objWidth) / 2);
					}
					$this.css("top", (parentHeight - objHeight) / 2);
				}
			});
		},
		//input获取/失去焦点
		focusBlur: function(obj) {
			obj.each(function() {
				var objVal = $(this).val();
				$(this).focus(function() {
					if ($(this).val() == objVal) {
						$(this).val("");
					}
				});
				$(this).blur(function() {
					if ($(this).val() == "") {
						$(this).val(objVal);
					}
				});
			});
		},
		//加载JS
		loadScript: function(file) {
			var script = document.getElementsByTagName("script")[0];
			var newjs = document.createElement("script");
			newjs.src = file;
			script.parentNode.insertBefore(newjs, script);
		},
		//去除空格   type 1-所有空格  2-前后空格  3-前空格 4-后空格
		trim: function(str, type) {
			switch (type) {
				case 1:
					return str.replace(/\s+/g, "");
				case 2:
					return str.replace(/(^\s*)|(\s*$)/g, "");
				case 3:
					return str.replace(/(^\s*)/g, "");
				case 4:
					return str.replace(/(\s*$)/g, "");
				default:
					return str;
			}
		},
		//检测字符串类型
		checkType: function(str, type) {
			switch (type) {
				case 'email':
					return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
				case 'phone':
					return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
				case 'tel':
					return /((\d{3,4})|\d{3,4}-|\s)?\d{7,14}$/.test(str);
				case 'number':
					return /^[0-9]$/.test(str);
				case 'english':
					return /^[a-zA-Z]+$/.test(str);
				case 'chinese':
					return /^[\u4E00-\u9FA5]+$/.test(str);
				case 'lower':
					return /^[a-z]+$/.test(str);
				case 'upper':
					return /^[A-Z]+$/.test(str);
				case 'qq':
					return /^[1-9]\d{4,10}$/.test(str);
				case 'zipcode':
					return /[1-9]\d{5}(?!\d)/.test(str);
				case 'url':
					return /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/.test(str);
				default:
					return true;
			}
		},
		//数据类型判断
		isType: function(o, type) {
			if (type) {
				var _type = type.toLowerCase();
			}
			switch (_type) {
				case 'string':
					return Object.prototype.toString.call(o) === '[object String]';
				case 'number':
					return Object.prototype.toString.call(o) === '[object Number]';
				case 'boolean':
					return Object.prototype.toString.call(o) === '[object Boolean]';
				case 'undefined':
					return Object.prototype.toString.call(o) === '[object Undefined]';
				case 'null':
					return Object.prototype.toString.call(o) === '[object Null]';
				case 'function':
					return Object.prototype.toString.call(o) === '[object Function]';
				case 'array':
					return Object.prototype.toString.call(o) === '[object Array]';
				case 'object':
					return Object.prototype.toString.call(o) === '[object Object]';
				case 'nan':
					return isNaN(o);
				case 'elements':
					return Object.prototype.toString.call(o).indexOf('HTML') !== -1
				default:
					return Object.prototype.toString.call(o)
			}
		},
		//判断页面是否有这个元素
		isHave: function(selectors) {
			var selectors = (typeof selectors == 'string') ? [selectors] : selectors,
				isHave;
			for (var i = 0; i < selectors.length; i++) {
				var selector = selectors[i];
				if (selector.length > 0) {
					isHave = true;
					break;
				}
			};
			return isHave;
		},
		//生成指定范围随机数
		randomNum: function(min, max) {
			return Math.floor(min + Math.random() * (max - min));
		},
		//显示隐藏密码
		togglePassword: function(input) {
			"password" == input.attr("type") ? input.attr("type", "text") : input.attr("type", "password");
		},
		//获取URL参数 只适用于/User/vip_card_manager?useless=219
		getQueryString: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return r[2];
			return '';
		},
		//隐藏部分姓名或者电话号码
		hiddenStr: function(str, frontLen, endLen) {
			var len = str.length - frontLen - endLen;
			var xing = '';
			for (var i = 0; i < len; i++) {
				xing += '*';
			}
			return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
		},
		//首页两侧广告
		asideAdv: function(leftAdvUrl, lefBigAdv, leftSmallAdv, rightAdvUrl, rightBigAdv, rightSmallAdv, time, same) {
			var leftAdvUrl = leftAdvUrl;
			var lefBigAdv = lefBigAdv;
			var leftSmallAdv = leftSmallAdv;
			var rightAdvUrl = rightAdvUrl;
			var rightBigAdv = rightBigAdv;
			var rightSmallAdv = rightSmallAdv;
			var asideAdv =
				'<div id="leftAdv" class="advImg"> <div class="leftAdvs adv"> <a href="' + leftAdvUrl + '" class="advs" target="_blank"><img src="' + lefBigAdv +
				'" /><i></i></a> </div> <a href="javascript:" class="closeLeftAdv" target="_self">关闭</a> </div> <div id="rightAdv" class="advImg"> <div class="rightAdvs adv"> <a href="' + rightAdvUrl + '" class="advs" target="_blank"><img src="' + rightBigAdv +
				'" /><i></i></a> </div> <a href="javascript:" class="closeLeftAdv" target="_self">关闭</a> </div> </div>';

			$("body").append(asideAdv);

			var num = time - 1; //倒计时的秒数
			var same = same; //左右是否相同的广告

			var Adv = window.setInterval(sidebarAdv, 1000);

			function sidebarAdv() {
				if (num == 0) {
					window.clearInterval(Adv);
					$(".leftAdvs").find("img").attr("src", leftSmallAdv);
					$(".rightAdvs").find("img").attr("src", rightSmallAdv);
				}
				num--;
			};

			if (same) {
				$("body").on("mouseenter", ".adv", function() {
					$(".adv").find("img").attr("src", lefBigAdv);
				});
				$("body").on("mouseout", ".adv", function() {
					$(".adv").find("img").attr("src", leftSmallAdv);
				});
			} else {
				$(".advImg").find("div").removeClass("adv");
				$("body").on("mouseenter", ".leftAdvs", function() {
					$(this).find("img").attr("src", lefBigAdv);
				});
				$("body").on("mouseout", ".leftAdvs", function() {
					$(this).find("img").attr("src", leftSmallAdv);
				});

				$("body").on("mouseenter", ".rightAdvs", function() {
					$(this).find("img").attr("src", rightBigAdv);
				});
				$("body").on("mouseout", ".rightAdvs", function() {
					$(this).find("img").attr("src", rightSmallAdv);
				});
			}

			$(".closeLeftAdv").on("click", function() {
				$(this).parents(".advImg").hide();
			});
		},
		//判断IE版本号
		isOnceIE9: function() {
			var bStrMic = navigator.appName == "Microsoft Internet Explorer";
			if (!navigator.appVersion.split(";")[1]) {
				return false;
			} else {
				var v = navigator.appVersion.split(";")[1].replace(/[ ]/g, "");
			}
			if (bStrMic && v == "MSIE6.0") {
				return 6;
			} else if (bStrMic && v == "MSIE7.0") {
				return 7;
			} else if (bStrMic && v == "MSIE8.0") {
				return 8;
			} else if (bStrMic && v == "MSIE9.0") {
				return 9;
			}
		},
		//单行文字逐条向上滚动
		txtScroll: function(obj, speed, time, height) {
			var obj = obj;
			var speed = speed;
			var height = obj.children().height();
			var time = time;
			var t = 0;
			var start = function() {
				t = setInterval(function() {
					obj.stop().animate({
						"margin-top": "-" + height + "px"
					}, speed, function() {
						Math.abs(parseInt($(this).css("margin-top"))) >= height && ($(this).css("margin-top", 0), $(this).find("li").slice(0, 1).appendTo($(this)))
					})
				}, time);
			};
			var stop = function() {
				clearInterval(t);
			};
			start();
			obj.hover(function() {
				stop();
			}, function() {
				start();
			});
		},
		//单行文字逐条向上滚动
		scrollText: function(obj) {
			var $uList = obj;
			var timer = null;

			$uList.hover(function() {
				clearInterval(timer);
			}, function() {
				timer = setInterval(function() {
					scrollList($uList);
				}, 3000);
			}).trigger("mouseleave");


			//滚动动画
			var scrollList = function(obj) {
				var scrollHeight = $("ul li:first").height();
				$uList.stop().animate({
					marginTop: -scrollHeight
				}, 600, function() {
					$uList.css({
						marginTop: 0
					}).find("li:first").appendTo($uList);
				});
			}
		},

		//单行逐条向上滚动
		oneScroll: function(obj, speed, time, height) {
			var obj = obj;
			var speed = speed;
			var height = obj.children().height();
			var time = time;
			var t = 0;
			var start = function() {
				t = setInterval(function() {
					obj.stop().animate({
						"margin-top": "-" + height + "px"
					}, speed, function() {
						Math.abs(parseInt($(this).css("margin-top"))) >= height && ($(this).css("margin-top", 0), $(this).find("li").slice(0, 1).appendTo($(this)))
					})
				}, time);
			};
			var stop = function() {
				clearInterval(t);
			};
			start();
			obj.hover(function() {
				stop();
			}, function() {
				start();
			});
		},

		//在body可视区里移动DIV
		move:function(obj){
			// 获取元素和初始值
			var oBox = obj,
				disX = 0,
				disY = 0;
			// 获取浏览器可见区域宽高，div宽高
			var browserWidth = $(window).width(),
				browserHeight = $(window).height(),
				boxWidth = oBox.width(),
				boxHeight = oBox.height();
			// 容器鼠标按下事件
			oBox.mousedown(function(e){
				var e = e || window.event;
				// 鼠标相对于div左侧位置
				disX = e.clientX - this.offsetLeft;
				disY = e.clientY - this.offsetTop;
				$(document).mousemove(function(e){
					var e = e || window.event;
					oBox.css('left',(e.clientX - disX) + 'px');
					if ((e.clientX - disX) <= 0) {
						oBox.css('left',0);
					} else if ((boxWidth - disX + e.clientX) >= browserWidth) {
						oBox.css('left',browserWidth - boxWidth + "px");
					}
					oBox.css('top',(e.clientY - disY) + 'px');
					if ((e.clientY - disY) <= 0) {
						oBox.css('top',0);
					} else if ((boxHeight - disY + e.clientY) >= browserHeight) {
						oBox.css('top',browserHeight - boxHeight + "px");
					}
				});
				$(document).mouseup(function(e){
					$(document).unbind();
				});

				return false;
			});
		}

	}
})();
