﻿function isIE(){ return $.browser.msie; }
function isIE6(){ return  isIE() && $.browser.version == '6.0'; }
function U(url){ return url.indexOf('http://') === 0 ? url : baseUrl+'/'+(url.indexOf('/') === 0 ? url.substr(1) : url)}
function T(url){ return url.indexOf('http://') === 0 ? url : themeRoot+'/'+(url.indexOf('/') === 0 ? url.substr(1) : url)}
function B(url){ return url.indexOf('http://') === 0 ? url : baseRoot+'/'+(url.indexOf('/') === 0 ? url.substr(1) : url)}
function randomUrl(url){return url += ((url = U(url)).indexOf('?') > -1 ? '&' : '?')+'__rndurl'+Math.random()*10000;}
function RELOAD(){window.location.reload(true);}
function strToInt(str) {return isNaN(str = parseInt(str)) ? 0 : str;}
$.extend(Array.prototype, {
	filter : function(func) {
		var clone = [], i = 0, j = this.length;
		for (;i<j; i++) {
			if (func) {
				isFunction(func) ?
					func.apply(this[i], [this[i]]) === true && clone.push(this[i]) :
					val != func && clone.push(this[i]);
			} else if (this[i]) {
				clone.push(this[i]);
			}
		}
		return clone;
	}
});

$.extend(String.prototype, {
	trim : function(){ return this.replace(/(^ *)|( *$)/g,''); },
	ucfirst : function(){ return this.substr(0, 1).toUpperCase()+this.substr(1)}
});

$.fn.extend({
	autoSize : function(width, height, func) {
		return this.removeAttr('height').removeAttr('width').each(function(){
			var $this = $(this);
			if (!$this.is('img')) return;
			this.complete && $.fn.autoSize.func.apply(this, [{data:{width:width, height:height, center:func}}]);
			$this.unbind('load', $.fn.autoSize.func).bind('load', {width:width, height:height, center:func}, $.fn.autoSize.func)
		});
	},
	
	fixed : function(left, top, animate){
		if (left === false) {
			this.removeAttr('fixed').pos('abs');
		} else {
			left = left || strToInt(this.css('left'));
			top  = top  || strToInt(this.css('top'));
			this.attr('fixed', 1).pos('abs');
			(isIE6() || animate) && windowChange(function(){
				if (this.attr('fixed')) {
					this.css({top:top+WIN.scrollTop(),left:left+WIN.scrollLeft()});
				}
			}, this) || this.css({position:'fixed'});
		}
		return this;
	},
	
	pngbg : function(url){
		isIE()
			&& this.css({filter:'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=bEnabled,sizingMethod=scale,src='+url+')'})
			|| this.css({background:'url('+url+')','-moz-background-size':'100% 100%','background-size':'100% 100%'});
		return this;
	},
	
	beforeLayer : function($node){
		var zIndex = $node.offsetParent().css('zIndex');
		zIndex == 'auto' && (zIndex = 0);
		return this.css('zIndex',++zIndex);
	},
	
	nearLayer : function(layer){
		return this.each(function(){
			var $this = $(this), elPos = layer.offset(), x, y;
			WIN.height() / 2 > elPos.top - $(document).scrollTop() ?
				y = elPos.top + layer.outerHeight() :
				y = elPos.top - $this.outerHeight();
			WIN.width() / 2 > elPos.left - $(document).scrollLeft() ?
				x = elPos.left: 
				x = elPos.left - $this.outerWidth() + layer.outerWidth();
			$this.css({ position: 'absolute', left: x, top: y})
		});
	},
	
	maxChildSize : function(type, thisWidth){
		var size = 0, children = this.children();
		children.each(function(){
			var childWidth = $(this)[type]();
			if (childWidth > size) size = childWidth;
		});
		if (thisWidth && size < thisWidth) size = thisWidth;
		children[type](size);
		return size;
	},
	
	childSize : function(type) {
		var size = 0;
		this.children().each(function(){
			size += $(this)['outer'+type.ucfirst()]();
		});
		return this[type](size);
	},
		
	center : function(offset){
		return this.each(function(){
			var $this = $(this), top, left;
			if (offset === true) {
				offset = $this.offsetParent();
				top   = (offset.height() - $this.height()) / 2,
				left  = (offset.width() - $this.width()) / 2;
			} else {
				top   = (WIN.height() - $this.height()) / 2,
				left  = (WIN.width() - $this.width()) / 2;
			}
			if (left < 0) left = 0;
			if (top < 0) top = 0;
			top  += $(offset || document).scrollTop();
			left += $(offset || document).scrollLeft();
			$(this).css({top : top + 'px',left : left + 'px'});
		});
	},
	
	pos : function(type){
		return this.each(function(){
			type ?
				$(this).css('position','absolute') :
				$(this).css('position') == 'static' ? $(this).css('position','relative') : '';
		})
	},
	
	enter : function(func){
		return this.bind('keydown',function(e){
			if (e.keyCode == 13 && isFunction(func)) {
				func.apply(this, [e]);
			}
		});
	},
	
	stopClick : function(){
		return this.click(function(e){
			e.stopPropagation();
		});
	},
	
	active : function(cls, siblings){
		!cls && (cls = 'active');
		return this.each(function(){
			siblings ? 
				siblings.removeClass(cls) :
				$(this).siblings().removeClass(cls);
			$(this).addClass(cls)
		});
	},
	
	selectNone : function(){
		return this.css({'-moz-user-select':'-moz-none'}).each(function(){
			this.onselectstart = function(){return false;}
		})
	},
	
	move : function (setting){
		setting = $.extend({
			cursor     : 'move',             //可移动元素的鼠标样式
			notEqual   : 'a',                //不参加移动的元素的选择器
			virtualBox : false,              //是否以虚线框移动
			direction  : 'auto',             //可移动方向
			startLen   : 10,                 //开始移动步长
			rect       : false,              //矩型泛围
			autoZindex : true,
			start      : function(){},
			move       : function(){},
			stop       : function(){}
		}, setting || {});
	
		return this.css({position:'absolute'}).each(function(){
			var $this  = $(this),
				rect   = setting.rect,
				header = setting.header ? $this.find(setting.header) : $this,
				target = $(setting.target || $this).pos('abs');
			var isMouseDown, isDraw, targetLeft, targetTop, clientX, clientY, left, top;
			$this.mousedown(function(e){
				if (setting.autoZindex) {
					jQuery.fn.move.prototype.zIndex = (jQuery.fn.move.prototype.zIndex || 1000) + 1;
					target.css({zIndex : jQuery.fn.move.prototype.zIndex});
				}
			}).mousedown();
			header.css({cursor : setting.cursor}).mousedown(function(e){
				if (!$(e.target).is(setting.notEqual)) {
				//	e.preventDefault();
					isMouseDown = true;
					clientX     = e.clientX;
					clientY     = e.clientY;
					targetLeft  = strToInt(target.css('left'));
					targetTop   = strToInt(target.css('top'));
					ofpar = target.offsetParent();
					ofpar.is('body') && (ofpar = $(document));
					setting.rect === true && (rect = [0,0,ofpar.width()-target.width(),ofpar.height()-target.height()]);
					return false;
				}
			}).selectNone();
			if (setting.virtualBox) {
				var virtualBox = $('<div><div style="width:100%;height:100%"></div></div>')
						.css({border:'4px solid #aaa',position:'absolute',cursor:setting.cursor}).insertAfter(target).hide();
			}
			$(document).bind('mousemove',function(e){
				if (isMouseDown) {
					if (isDraw) {
						left = e.clientX - clientX + targetLeft;
						top  = e.clientY - clientY + targetTop;
						setting.direction == 'x' && (top  = targetTop);
						setting.direction == 'y' && (left = targetLeft);
						if (isArray(rect)) {
							left < rect[0] && (left = rect[0]);
							top  < rect[1] && (top  = rect[1]);
							left > rect[2] && (left = rect[2]);
							top  > rect[3] && (top  = rect[3]);
						}
						if (setting.move.apply(target,[e, {left:left,top:top}, rect]) !== false) {
							(setting.virtualBox ? virtualBox : target).css({left:left,top:top}); 
						}
					} else if(Math.abs(e.clientX - clientX) > setting.startLen || Math.abs(e.clientY - clientY) > setting.startLen) {
						isIE() && header[0].setCapture();
						isDraw = true;
						setting.start.apply(target,[e, {left:left,top:top}, rect]);
						if (setting.virtualBox) {
							virtualBox.show()
								.css({zIndex:jQuery.fn.move.prototype.zIndex+1,width:target.width()-8,height:target.height()-8});
						}
					}
				}
			}).bind('mouseup',function(e){
				if (isMouseDown) {
					if (isDraw) {
						if (setting.virtualBox) {
							virtualBox.hide();
							target.css({left:virtualBox.css('left'),top:virtualBox.css('top')});
						}
						setting.stop.apply(target,[e, {left:left,top:top}, rect]);
					}
					isIE() && header[0].releaseCapture();
					isMouseDown = isDraw = false;
				}
			});
		});
	},

	controller : function(){
		if (this.data('controllering')) return false;
		var func = $(this).attr('href').replace('controller://', ''), p = func.split('_'), This = this,
			controller = p[0], action = p[1], data = call(p.join('.'));
		if (data === false) return;
		this.data('controllering', 1);
		v.ajax.server(U(controller+'/'+action), {data:data}, [function(response, text){
			callback(p.join('.'), response.data);
		}, function(){ This.removeData('controllering'); }]);
	}
});

$.fn.autoSize.func = function(e){
	var $this = $(this), img = $('<img/>').attr({src:$this.attr('src')})[0], width = e.data.width, height = e.data.height,
		_width = height / img.height * img.width, _height = width / img.width * img.height;
	width < _width && (height = _height) || (width = _width);
	$this.css({width:width, height:height});
	isFunction(e.data.center) && e.data.center.apply($this, [width, height]);
}

~function(){
	var checkType = ['Object','Array','Function','String','Boolean','Number'],
		checkExtend = new Object;
	for (var i = 0,j = checkType.length; i < j; i++) {
		(function( str ){
			window['is'+str] = function( check ){
				return Object.prototype.toString.call(check) == '[object '+str+']';
			}
		})(checkType[i]);
	}
}();

function filterCode(str){
	return (str || '').toString().replace(/\\/g,'\\\\').replace(/\"/g,'\\"').replace(/\n/g,'\\n').replace(/\r\n/g,'\\r\\n').replace(/\r/g,'\\r').replace(/\t/g,'\\t');
}

function jsonEncode(object){
	var jsonArray = [],	jsonStr = '';
	if (isArray(object)) {
		$.each(object || [],function(i,val){
			if (isObject(val) || isArray(val)) {
				jsonArray.push(jsonEncode(val));
			} else if (isNumber(val)) {
				jsonArray.push(val);
			} else {
				jsonArray.push('"'+filterCode(val)+'"');
			}
		});
		return '['+jsonArray.toString()+']';
	} else if (isObject(object) && object !== undefined) {
		$.each(object,function(key,val){
			jsonStr = '"'+key+'":';
			if (val !== undefined && isObject(val) || isArray(val)) {
				jsonArray.push(jsonStr + jsonEncode(val));
			} else if (isNumber(val)) {
				jsonArray.push(jsonStr + val);
			} else {
				jsonArray.push(jsonStr + '"'+filterCode(val)+'"');
			}
		});
		return '{'+jsonArray.toString()+'}';
	}
}

function jsonDecode(str){
	try{
		str = (str || '').replace(/\\u[A-z0-9]{4}/g,function($1){ return unescape($1.replace('\\','%')); }).trim();
		if (str.indexOf('{') === 0 || str.indexOf('[') === 0) return eval("("+str+")");
	}catch(e){
		return '';
	}
}

$(function(){
var func = [];
$(window).bind('scroll resize',function(){
	$.each(func,function(k, func){
		func[0].call(func[1]);
	});
});
window.windowChange = function(f, apply){
	f.call(apply);
	return func.push([f, apply]);
}
});

function cookie(name, value, expires){
	if (value !== undefined) { 
		if (value === null) { 
			value = ''; 
			expires = -1; 
		} 
		var path = '', domain = '', secure = ''; 
		if (expires && (typeof expires == 'number' || expires.toUTCString)) { 
			var date = expires; 
			if (typeof expires == 'number') { 
				date = new Date(); 
				date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000)); 
			}
			expires = '; expires=' + date.toUTCString(); 
		} 
		document.cookie = [name, '=', encodeURIComponent(value), expires, path && '; path='+path, domain && '; domain='+domain, secure && '; secure'].join(''); 
	} else { 
		var cookieValue = null; 
		if (document.cookie && document.cookie != '') { 
			var cookies = document.cookie.split(';'); 
			for (var i = 0; i < cookies.length; i++) { 
				var cookie = jQuery.trim(cookies[i]); 
				if (cookie.substring(0, name.length + 1) == (name + '=')) { 
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
					break; 
				} 
			} 
		} 
		return cookieValue; 
	}
}

var v = y = {};

var DOC = $(document),BODY = $('body'), WIN = $(window);
//创建KIT组件时进行扩展
y.apply = function(kit, key){
	if (isObject(key)) {
		y.extend(kit.prototype, key);
	}
}
	
var kitExtendend = {
	appendTo : function(kit) {
		if (kit.isKit && kit.dom && this.dom) {
			this.dom.appendTo(kit.dom);
			this.parent = kit;
			this.beforeAppend && this.beforeAppend.call(this);
		//	this.setWidthFromChild && this.setWidthFromChild();
		}
		return this;
	},
	append   : function(kit) {
		if (kit.isKit && kit.dom && this.dom) {
			this.dom.append(kit.dom);
			kit.parent = this;
			this.beforeAppend && this.beforeAppend.call(this);
		//	this.setWidthFromChild && this.setWidthFromChild();
		}
		return this;
	},
	width : function(width){
		return this.dom.css({width:width}), this;
	},
	height : function(height){
		return this.dom.css({height:height}), this;
	},
	bind : function(evt, func){
		var This = this;
		return this.dom.bind(evt, function(e){
			return func.apply(This, [e]);
		}), this;
	}
}

var kits = {};

y.kit = function(kitName, func, extend ){
	var tkit = this;
	if (!this.kit[kitName]) {
		extend = func;
		func   = new Function();
		func.extend = function(ext){
			return v.apply(func, ext);
		}
		func.apply = function(ext){
			return v.kitExtend(func, ext);
		}
		y.kit[kitName] = func;
		y.kitGroup[kitName] = [];
		func.extend(kitExtendend);
		func.extend(extend);
	} else {
		func = func || {};
		if (func.id && kits[func.id]) {
			return kits[func.id];
		}
		var kit   = new this.kit[kitName](func);
		kit.isKit = true;
		kit.settings = func;
		if (kit.initComplete && kit.initComplete(func, kitName, kit) !== false) {
			$.each(func, function(key, val){
				isFunction(kit[key]) && kit[key](val);
			});
		}
		func.id && (kits[func.id] = kit);
		this.kitGroup[kitName].push(kit);
		var destory = kit.destory;
		kit.destory = function(){
			if (!isFunction(destory) || destory.apply(kit) !== false) {
				this.dom && this.dom.remove();
			}
			if (func.id && kits[func.id]) {
				delete window.kits[func.id]	;
			}
			$.each(tkit.kitGroup[kitName],function(k,v){
				v === kit && delete tkit.kitGroup[kitName][k];
			});
		}
		return kit;
	}
}

y.kitExtend = function(dstFunc, ext){
	if (isFunction(dstFunc) && isObject(ext)) {
		var dp = dstFunc.prototype,
			nf = function(){};
		nf.prototype = dp;
		dstFunc = new nf();
		y.extend(dstFunc, ext);
		dstFunc.superClass = dp;
		return dstFunc;
	}
}

y.extend = $.extend;
y.util     = {};
y.kitGroup = {};
y.ajax     = {};
//系统扩展

$.extend(v.ajax,{
	ajax   : '',
	queues : [],
	get  : function(url, data, callback, type){
		this.ajax && this.ajax.abort();
		isFunction(data) && (type = callback, callback = data, data = {});
		var THIS = this;
		THIS.ajax = $.ajax({
			'type' : type || 'GET',
			'data' : data,
			'cache': false,
			'url'  : url,
			'success' : function(response){
				THIS.ajax = '';
				callback && callback.apply(this, arguments);
			},
			'complete' : function(){
				THIS.ajax = '';
				THIS.queues.length && THIS.get(THIS,THIS.queues.shift());
			},
			'error'    : function(response, textStatus){
 				THIS.ajax = '';
			}
		});
		return this.ajax;
	},
	server : function(url, data, cb, type, must){
		(isFunction(data) || isArray(data)) && (type = cb, cb = data, data = {});
		if (isArray(cb)) {
			must = cb[1]; cb = cb[0];
		}
		return this.get(url, data, function(text){
			var response = jsonDecode(text);
			if (response){
				callback(response.msg, response.data) !== false && cb && cb.apply(this, [response, text]);
			} else {
				alert(text);
			}
			isFunction(must) && must();
		}, type || 'GET');
	},
	post : function(url, data, callback){
		return this.get(url, data, callback, 'POST');
	},
	queue : function(){
		!this.ajax && this.get.apply(this, arguments) || this.queues.push(arguments);
	}
});

$.extend(v.util, {
	co : function(){
		var object = new Object;
		$.each(arguments, function(i, ary){
			object[ary[0]] = ary[1];
		});
		return object;
	},
	setHome : function(){
		if ($.browser.msie) {
			document.body.style.behavior='url(#default#homepage)';
			document.body.setHomePage(location.href);
		}else {
			alert('您的浏览器不支持该操作!');
		}
	},
	addFavorite : function(url, title){
		url   = url || location.href;
		title = title || document.title;
		try{
			if ($.browser.msie) {
				if ($.browser.version >= 8){
					external.AddToFavoritesBar(url, title, 'slice');
				} else {
					window.external.addFavorite(url, title);
				}
			} else {
				window.sidebar.addPanel(title, url, "");
			}
		} catch(e) {alert('您的浏览器不支持此操作')}
	},
	redirect : function(url) {
		window.location.href = url;
	},
	randomName : function(name) {
		return name+parseInt(Math.random()*10000).toString();
	}
});

v.kit('mast', {
	initComplete : function(settings){
		if (!settings) settings = {};
		settings.content && settings.content.pos();
		this.dom = $('<div/>').hide()
			.css({zIndex:100,left:0,top:0,background:'#000',opacity:0.4}).pos('abs');
	},
	show : function(content){
		if (content) {
			var width = content[0].scrollWidth, height = content[0].scrollHeight;
		} else {
			var content = $('body'), width = DOC.width(), height = DOC.height(); 
		}
		return this.dom.show().appendTo(content).css({height:height,width:width}), this;
	},
	hide : function(){
		this.dom.remove();
	}
});

y.kit('window',{
	initComplete : function(settings, kitName, kthis){
		kthis.dom = $(tpl.window).appendTo('body').pos('abs').hide();
		$.extend(this, {
			titleNode : kthis.dom.find('.title'),
			contentNode : kthis.dom.find('.content'),
			closeNode : kthis.dom.find('.close'),
			btn : kthis.dom.find('.button_layout')
		});
		kthis.closeNode.click(function(){
			kthis.destory();
		});
		kthis.layer = settings.layer;
		if (settings.url) {
			kthis.contentNode.load(settings.url);
		}
		kthis.dom.move({header : '.title:eq(0)',not : '.close'});
	},
	button : function(btn){
		btn.dom.appendTo(this.btn);
		this.btn.show();
		return this;
	},
	title : function(str) {
		return (this.textNode || (this.textNode = this.titleNode.find('h3'))).empty().append(str);
	},
	content : function(html) {
		if (html && html.isKit) {
			html.dom.appendTo(this.contentNode.empty());
		} else {
			return this.contentNode.empty().append(html).append();
		}
	},
	show : function(){
		if (isIE6()) {
			this.hideSelect = $('select:visible').not(this.dom.find('select')).hide();
		}
		this.layer && v.kit('mast', {id:'window'}).show();
		this.dom.is(':hidden') && this.dom.show().center();
		return this;
	},
	destory : function(){
		this.hideSelect && this.hideSelect.show();
		if (this.layer) {
			v.kit('mast', {id:'window'}).hide();
		}
	}
});

function tpl(strings, rp){
	if (rp !== undefined && isObject(rp)) {
		strings = strings.replace(/\{(.+?)\}/g,function(v, k){
			return rp[k] ? rp[k] : '';
		});
	}
	return strings;
}

$.extend(tpl, {
	'window' : '<div class="layer"><div class="title"><a href="#" class="close"></a><h3>图片上传</h3></div><div class="detail"><div class="content"></div><div class="button_layout fixed" style="display:none;"></div></div></div>'
});

if (isIE6()) {
	$('label').live('mouseup', function(){
		$(this).find('input').focus().click();
	});
	$('label input').live('mouseup', function(){return false;});
}

var call = function(controller, func){
	if (isFunction(func)) {
		controller = controller.split('.');
		if (!call[controller[0]]) {
			call[controller[0]] = {}
		}
		call[controller[0]][controller[1]] = func;
	} else if (isString(controller)) {
		var args = controller = controller.split('.'),
			action = controller[1] || controller[0];
		controller = controller[1] ? controller[0] : window.controller;
		if (call[controller] && call[controller][action]) {
			args.shift();
			args.shift();
			return call[controller][action].apply(this, args);
		}
	}
	return '';
}, callback = function(controller, func){
	if (isFunction(func)) {
		controller = controller.split('.');
		if (!callback[controller[0]]) {
			callback[controller[0]] = {}
		}
		if (!callback[controller[0]][controller[1]]) callback[controller[0]][controller[1]] = [];
		callback[controller[0]][controller[1]].push(func);
	} else if (isString(controller)) {
		controller = controller.split('.');
		var action = controller[1] || controller[0], rtv;
		controller = controller[1] ? controller[0] : window.controller;
		if (callback[controller] && callback[controller][action]) {
			for(var i = 0, j = callback[controller][action].length-1; i <= j; j--) {
				if (callback[controller][action][j](func) === false) return false;
			}
		}
	}
};

$('input').live('keydown', function(e){
	if (e.keyCode == 13) {
		var form = $(this).parents('form:eq(0)');
		if (!form.length || !isIE6()) return;
		form.submit();
		return false;
	}
});

$('textarea').live('keydown', function(e){
	if (e.ctrlKey && e.keyCode == 13) {
		var form = $(this).parents('form:eq(0)');
		form.length && form.submit();
	}
});

$('a[href^=controller://]').live('click', function(){ return $(this).controller(), false;});

$('.button,:button').live('click', function(){
	var form = $(this).parents('form:eq(0)');
	form.length && form.submit();
	return false;
});

