﻿(function($){var x=function(o){return o!==undefined&&o!==null;},H=$("head"),Z={},K={callback:"C",url:location.href};$.jsonp=function(d){d=$.extend({},K,d);if(x(d.beforeSend)){var t=0;d.abort=function(){t=1;};if(d.beforeSend(d,d)===false||t)return d;}
var _="",y="success",n="error",u=x(d.url)?d.url:_,p=x(d.data)?d.data:_,s=(typeof p)=="string",k=function(f){setTimeout(f,1);},S,P,i,j,U;p=s?p:$.param(p);x(d.callbackParameter)&&(p+=(p==_?_:"&")+escape(d.callbackParameter)+"=?");!d.cache&&!d.pageCache&&(p+=[(p==_?_:"&"),"_xx",(new Date()).getTime(),"=",1].join(_));S=u.split("?");if(p!=_){P=p.split("?");j=S.length-1;j&&(S[j]+="&"+P.shift());S=S.concat(P);}
i=S.length-2;i&&(S[i]+=d.callback+S.pop());U=S.join("?");if(d.pageCache&&x(Z[U])){k(function(){if(x(Z[U].e)){x(d.error)&&d.error(d,n);x(d.complete)&&d.complete(d,n);}else{var v=Z[U].s;x(d.dataFilter)&&(v=d.dataFilter(v));x(d.success)&&d.success(v,y);x(d.complete)&&d.complete(d,y);}});return d;}
var f=$("<iframe />");H.append(f);var F=f[0],W=F.contentWindow||F.contentDocument,D=W.document;if(!x(D)){D=W;W=D.getParentNode();}
var w,e=function(_,m){d.pageCache&&!x(m)&&(Z[U]={e:1});w();m=x(m)?m:n;x(d.error)&&d.error(d,m);x(d.complete)&&d.complete(d,m);},t=0,C=d.callback,E=C=="E"?"X":"E";D.open();W[C]=function(v){t=1;d.pageCache&&(Z[U]={s:v});k(function(){w();x(d.dataFilter)&&(v=d.dataFilter(v));x(d.success)&&d.success(v,y);x(d.complete)&&d.complete(d,y);});};W[E]=function(s){(!s||s=="complete")&&!t++&&k(e);};w=function(){W[E]=undefined;W[C]=undefined;try{delete W[E];}catch(_){}
try{delete W[C];}catch(_){}
D.open()
D.write(_);
D.close();f.remove();
}
k(function(){D.write(['<html><head><script src="',U,'" onload="',E,'()" onreadystatechange="',E,'(this.readyState)"></script></head><body onload="',E,'()"></body></html>'].join(_));
																																																							  D.close();
																																																							  });d.timeout>0&&setTimeout(function(){!t&&e(_,"timeout");},d.timeout);d.abort=w;return d;}
$.jsonp.setup=function(o){$.extend(K,o);};})(jQuery);

//xydudu <xuedudu@gmail.com>
var hifly={	
	domChunk:'a.hiflybox, area.hiflybox, input.hiflybox', 	//hifly.box 触发DOM规则
	miniChunk:'a.minibox, area.minibox, input.minibox',		//hifly.miniBox 触发DOM规则
	delChunk:'a.delcommon,input.delcommon',					//hifly.delcommon 触发DOM规则
	ajaxChunk:'a.ajaxcommon,input.ajaxcommon', 				//一般ajax触发DOM规则
	
	//自动加载
	init:function(){
		hifly.box.init();
		hifly.miniBox.init();
		hifly.delCommon();
		hifly.ajaxcommon();
	},
	errmsg:'加载失败',
	
	//x-1-y-2类型字符串转为{x:1,y:2}对象
	id2Data:function(id){
		var arr=id.split('-'),l=arr.length,data={};
		for(var i=0;i<l;i=i+2){
			data[arr[i]]=arr[i+1];
		}
		return data;
	},
	//id2Data反作用
	data2Id:function(data){
		var arr=[];
		$.each(data,function(k,v){
			arr.push(k+'-'+v);
		})
		return arr.join('-');
	},
	replaceHtml:function(html,data){		
		return html.replace(/\#\$(\w+?)\$\#/g,function(x,y){return data[y]});
	},
	copyText:function(id) {
		var text2copy=$(id).val();
		$(id).select();
		$('body').xMsg('复制成功');
		if (window.clipboardData) {   
			window.clipboardData.setData("Text",text2copy);   
		 } else {   
				  var flashcopier = 'flashcopier';
				   if (!document.getElementById(flashcopier)){
						var divholder = document.createElement('div');
						divholder.id = flashcopier;
						document.body.appendChild(divholder);
					}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="http://js.hunantv.com/sq/public/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;	
 		}
	},
	doCopy : function(txt) {
		if (!txt)
			return false;
		if (window.clipboardData) {
			window.clipboardData.clearData();
			window.clipboardData.setData("Text", txt);
		} else if (navigator.userAgent.indexOf("Opera") != -1) {
			window.location = txt;
		} else if (window.netscape) {
			try {
				netscape.security.PrivilegeManager
						.enablePrivilege("UniversalXPConnect");
			} catch (e) {
				alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试");
				return false;
			}
			var clip = Components.classes['@mozilla.org/widget/clipboard;1']
					.createInstance(Components.interfaces.nsIClipboard);
			if (!clip)
				return false;
			var trans = Components.classes['@mozilla.org/widget/transferable;1']
					.createInstance(Components.interfaces.nsITransferable);
			if (!trans)
				return false;
			trans.addDataFlavor('text/unicode');
			var str = new Object();
			var len = new Object();
			var str = Components.classes['@mozilla.org/supports-string;1']
					.createInstance(Components.interfaces.nsISupportsString);
			var copytext = txt;
			str.data = copytext;
			trans.setTransferData("text/unicode", str, copytext.length * 2);
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip)
				return false;
			clip.setData(trans, null, clipid.kGlobalClipboard);
		}
		return true;
	}
};

/*
	弹出层，可定制位置，灵活性高
*/
hifly.miniBox={
	
	//层配置项，外部可配置w,h,pos
	settings:{
		w:'300px',	//层宽
		h:'100px',	//层高
		pos:'center',	//层位置
		left:0,		
		top:0,		
		aw:0,
		ah:0,
		a:false
	},	
	
	init:function(){
		var O=this;
		$(hifly.miniChunk).click(function(){			
			var url = this.href || this.alt;
			var type = this.rel || 'json';			
			var 
			classScan = /{(.*)}/.exec(this.className),
			s=classScan&&classScan[1].split(',')||false,			
			settings={};
			if(s){
				settings.w=s[0];
				settings.h=s[1];
				settings.pos=s[2];
			}
			/*
			settings=$.extend(settings,$(this).offset())			
			settings.aw=$(this).width();
			settings.ah=$(this).height();
			*/
			settings.a=$(this);
			O.settings=$.extend(O.settings,settings);			
			O.getContent(url,type);
			this.blur();
			return false;
		});
	},
	
	//获取数据
	getContent:function(href,type){
		this.show(null);
		var box=$('#minibox');
		if(href.match(/#/)){
			var url    = window.location.href.split('#')[0];
			var target = href.replace(url,'');			
			box.html($(target).html());
		}else{
			$.ajax({
				type:"POST",
				url:href,
				data:{ajax:true},
				dataType:type,
				success:function(data){					
					var html='';
					if(typeof data=='object'){
						if(data.err) return false;
						html=data.msg||hifly.errmsg;						
					}else{
						html=data;
					}
					box.html(html);					
				}
			});	
		}
		this.setDiv();
	},
	
	//显示层
	show:function(html){
		if($('#minibox').length) return;
		$('body').prepend('<div id="minibox"></div>');
		if(html != null){			
			$('#minibox').html(html);
		}else{
			$('#minibox').html("<div class='loadminibox'>正在载入，请稍候...</div>");
		}
		this.setDiv();
	},
	
	//定位层
	setDiv:function(){
		var minibox=$('#minibox'),settings=this.settings;
		minibox.css({width:settings.w,height:settings.h});
		var viewWH=$.viewSize(),top=0,left=0;
		if(settings.a){
			var 
			offset=settings.a.offset(),
			aw=settings.a.width();
			ah=settings.a.height();
		}else{
			settings.pos='center';
		}
		switch(settings.pos){
			case 'center':
				var ts=$.getPageScroll();				
				top = 0.5 * (viewWH[1]-parseInt(settings.h))-100+ts[1];
				top=top<10?10:top
				left = 0.5 * (viewWH[0]-parseInt(settings.w));				
			break;
			case 'left':
				top=offset.top;
				left=(offset.left-parseInt(settings.w))-10;
				left=left<10?10:left;
			break;
			case 'right':
				top=offset.top;
				left=(parseInt(aw)+offset.left)+10;
			break;
			case 'bottom':
				top=(parseInt(ah)+offset.top)+10;
				left=offset.left;
			break;
			case 'top':
				top=(offset.top-parseInt(settings.h)-10);
				top=top<10?10:top
				left=offset.left;
			break;
		}
		minibox.css({top:top,left:left});
	},
	closeBox:function(){
		//$('#minibox').unbind('click');
		$('#minibox').remove();
		if (typeof document.body.style.maxHeight == "undefined") {//if IE6
			$('body','html').css({height: 'auto', width: 'auto'});
			$('html').css('overflow', '');
		}
		document.onkeydown = '';
		return false;
	}
}

/*
	弹出层，居中显示 (将整合到minibox)
*/
hifly.box={
	init:function(){
		var O=this;
		$(hifly.domChunk).click(function(){
			var t = this.title || this.name || null; 
			var a = this.href || this.alt;
			var type = this.rel || 'json';	
			O.preShow({title:t,url:a},type);
			this.blur();
			return false;
		});
	},	
	/*
		settings={title,url,html}
		title:标题
		url:ajax调用链接
		html:直接显示指定内容
	*/
	preShow:function(settings,type){
		var O=this;
		O.show(null);		
		var
		box=$('#hiflybox'),
		html=settings.title?['<div id="hiflybox-title">'+ settings.title +'</div>']:[],		
		href=settings.url;
		if(href.match(/#/)){
			var url    = window.location.href.split('#')[0];
			var target = href.replace(url,'');			
			box.html(html.join("\n")).append($(target).clone().show());
			O.refineBox();
		}else{
			$.ajax({
				type:"POST",
				url:href,
				data:{ajax:true},
				dataType:type,
				success:function(data){					
					if(typeof data=='object'){
						if(data.err) return false;
						html.push(data.msg||hifly.errmsg);						
					}else{
						html.push(data);
					}
					box.html(html.join("\n"));
					O.refineBox();
				}
			});	
		}
		
	},
	show:function(div){		
		if($('#hiflybox').length) return;
		$('body').prepend('<div id="overlay"></div><div id="hiflybox"></div>');		
		if(div != null){			
			$('#hiflybox').html(div);
		}else{
			$('#hiflybox').html("<div class='loadpop'>正在载入，请稍候...</div>");
		}
		this.setOverlay();
	},
	setOverlay:function(){		
		var oheight = ($.browser.msie?11:26),
		dialog=$('#hiflybox')[0],
		w=dialog.offsetWidth;		
		left=(document.body.offsetWidth-w)/2+'px';		
		$('#overlay').css({height:dialog.offsetHeight+oheight,width:w+26,left:left});
		dialog.style.left=left;		
	},
	closeBox:function(){
		$('#overlay').unbind('click');
		$('#hiflybox,#overlay').remove();
		if (typeof document.body.style.maxHeight == "undefined") {//if IE6
			$('body','html').css({height: 'auto', width: 'auto'});
			$('html').css('overflow', '');
		}
		document.onkeydown = '';
		return false;
	},
	//重新定位
	refineBox:function(){		
		//var agent = navigator.userAgent.toLowerCase();
		var top = 0.5 * ($.viewSize()[1] - $('#hiflybox')[0].offsetHeight)+100;		
		if(!window.XMLHttpRequest) top=''; //IE 6		
		$('#hiflybox,#overlay').css('top', top);
		this.setOverlay();
	}
}

//删除通用
hifly.delCommon=function(){
	var box=hifly.miniBox;
	
	$(hifly.delChunk).click(function(){
		var url 	= this.href || this.alt;
		var delid	= this.rel || false;
		var _data	= hifly.id2Data(this.id);
		
		
		/**** html部分看如何设计 *****/
		var html = $('<div class="in-minibox"></div>'),
			t	 = this.title || '确定删除？',
			s	 = '<input type="button" value="确定" />',
			c	 = '<a href="javascript:" >取消</a>';
		html.html(t);
		
		$(s).bind('click',function(){			
			$(this).attr({'value':'正在提交...'});
			$.ajax({
				type:"POST",
				url:url,
				data:_data,
				dataType:'json',
				success:function(data){
					if(typeof data=='object'){						
						if(data.err){
							html.html('提交出错！<input type="button" onclick="hifly.miniBox.closeBox()" value="关闭" />');
						}else{
							html.html('提交成功！');
							setTimeout(function(){
								box.closeBox();
								$('#'+delid).fadeOut(300,function(){$(this).remove()});
							},300);
						}
					}else{
						html.html('提交出错！<input type="button" onclick="hifly.miniBox.closeBox()" value="关闭" />');
					}
				},
				error:function(msg){
					alert('提交失败');
				}
			});			
			return false;
		}).appendTo(html);
		
		$(c).bind('click',function(){
			hifly.miniBox.closeBox();
			return false;
		}).appendTo(html);
		
		box.settings.w='200px';
		box.settings.h='50px';
		box.settings.pos='left';
		box.settings.a=$(this);
		box.show(html);
		return false;
	});
}


hifly.ajaxcommon=function(){
	var box=hifly.miniBox;	
	$(hifly.ajaxChunk).click(function(){
		var a		= $(this);							  
		var url 	= this.href || this.alt;
		var _data	= hifly.id2Data(this.id);
		var callback= this.rel && eval(this.rel) || false;		
		
		$.ajax({
			type:"POST",
			url:url,
			data:_data,
			dataType:'json',
			success:function(data){
				if(typeof data=='object'){
					if(data.err){
						box.show('<div class="in-minibox">提交出错！<input type="button" onclick="hifly.miniBox.closeBox()" value="关闭" /></div>');
					}else{
						callback&&callback(a);
					}
				}else{
					box.show('<div class="in-minibox">提交出错！<input type="button" onclick="hifly.miniBox.closeBox()" value="关闭" /></div>');
				}
			},
			error:function(msg){
				box.show('<div class="in-minibox">提交出错！<input type="button" onclick="hifly.miniBox.closeBox()" value="关闭" /></div>');
			}
		});
		return false;
	})
}

/*
	TAG选取
*/
hifly.tag=function(){
	var input=$('input.tag'),l=input.length,store=$('#tag-choose a');
	if(l==0)return;
	store.bind('click',function(){
		var tag=$(this).html();
		if(!checkTagInput(tag)){
			var k=input.filter(function(index){return this.value==''});
			if(k.length>0) k[0].value=tag;
		}
		return false;
	})
	var checkTagInput=function(_tag){
		var y=false;
		$.each(input,function(k,v){
			if(v.value==_tag){
				v.value='';
				y=true;
			}			
		})
		return y;
	}
}

/*
	获取屏幕大小
	return [宽,高] 
*/
$.viewSize = function(){
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined'){
		size = [window.innerWidth, window.innerHeight];
	}else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
	}else{
		size = [document.body.clientWidth, document.body.clientHeight];
	}
	return size;
}
/*
	屏幕滚动距离
	retuen [x,y]
*/
$.getPageScroll=function(){
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	
	return new Array(xScroll,yScroll) 
}
/*
	消息提示
*/
$.fn.extend({	
	xMsg:function(msg,param,callback){
		var defaluts={className:false,duration:2000,hide:true,span:true};
		if( typeof msg == 'object' ){
			param = msg;
			msg = 0;
		}		
		if(typeof param == 'number')defaluts.duration=param;
		param = $.extend({},defaluts,param);		
		var o=param.span?$("<span></span>"):this;
		o.html(param.msg||msg).addClass(param['className']||'').show().prependTo(param.span&&this);
		if(param.span&&!param['className']){
			o.css({
			position:'fixed',
			backgroundColor:'red',
			color:'#fff',
			fontSize:'13px',
			padding:'3px',
			top:'5px',
			right:'5px'	
			});
			if($.browser.msie&&$.browser.version==6){
				o.css({position:'absolute'});
			}
			if(!o.parent().is('html'))
				o.css({position:'absolute'}).parent().css({position:'relative'});
		}
		if(param.hide)hide();
		function hide(){
			setTimeout(
				function(){
					o.fadeOut(200,callback&&callback);
					param.span&&o.remove()
				},
				param.duration
			)
		}
	}	
});

/*
	Cookie 操作 @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
	清空表单
*/
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
                	v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

$(document).ready(function(){
	hifly.init();
	$('form').bind('submit',function(){
		$(this).children(':submit').attr('disabled','disabled');
	});
});