/**
 * @author poly 89490364a@gmail.com
 */
(function($){
	/**
	 * 增加子弹出窗
	 */
	$.fn.addPop=function(o)
	{
		o=o?o:{}
		
		function popup(e)
		{
			$(".subPop:visible").trigger("popdown");
			var that=$(this).show();
			var tooHight=that.innerHeight(true)>$(window).height();
			var tooLow=e.pos.y+that.innerHeight(true)>$(window).height();
			var css={left:e.pos.x-20,top:tooHight?0:!tooLow?e.pos.y-20:"auto",bottom:!tooHight&&tooLow?0:"auto"};
			that.css(css);
			e.stopPropagation();
		}
		
		function popdown(e)
		{
			var that=$(this);
			if(e.type=="popdown"||e.relatedTarget!=that.data("rel")[0])
			{
				//console.log("popdown",e.type,e.relatedTarget);
				that.hide();
			}
			e.stopPropagation();
		}
		
		function addSelect(e)
		{
			var that=$(this);
			that.data("rel").trigger(e);
			e.stopPropagation();
		}
		
		this.each(function(){
			var that=$(this);
			var cover=$("#cover");
			var subPop=$("<div class='subPop'/>");
			cover.append(subPop);
			subPop.data("rel",that)
				  .bind("popup",popup)
				  .bind("popdown",popdown)
				  .bind("mouseleave",popdown)
				  .bind("addSelect",addSelect)
				  /*.load(o.href,{countryId:that.attr("countryId")},function(){
				  	var event=new jQuery.Event("popup");
					event.pos=o.pos;
				  	$(this).trigger(event);
				  });*/
		    $.ajax({
				url:o.href,
				dataType:"html",
				data:{countryId:that.attr("countryId")},
				timeout:5000,
				success:function(data){
                    var event=new jQuery.Event("popup");
                    event.pos=o.pos;
                    subPop.html(data).trigger(event);
				},
                error:function(XMLHttpRequest,textStatus,errorThrown)
                {
                    alert("出错啦!\n错误代码："+(textStatus||errorThrown)+"\n请重试或者检查您的网络连接。");
                }
			});
			that.data("subPop",subPop);
		});
		return this;
		
	}
	
	$.fn.mselector=function(o)
	{
		o=o?o:{};
		
		/**
		 * 弹出关联的弹出窗口
		 */
		function popup(e)
		{
			var that=$(this);
			if(that.data("subPop"))
			{
			  	var event=new jQuery.Event("popup");
				event.pos={x:e.clientX,y:e.clientY};
				that.data("subPop").trigger(event);
			}
			else
			{
				that.addPop({href:o.href,pos:{x:e.clientX,y:e.clientY}});
			}
		}
		
		/**
		 * 关闭关联的弹出窗口
		 */
		function popdown(e)
		{
			var that=$(this);
			var subPop=that.data("subPop")
			if(subPop&&subPop.is(":visible"))
			{
				var inPop=subPop[0]==($(e.relatedTarget).parent(".subPop")[0]||e.relatedTarget);
				if(!inPop)
				{
					subPop.trigger("popdown");
				}
			}
			//e.stopPropagation();
		}
		
		function addSelect(e)
		{
			var that=$(this);
			//console.log(e.type,e.newNode,this)
			var container=$("thead td",this);
			if($(":radio",container).length)
			{
				container.children().trigger("click");
			}
			container.append(e.newNode);
			$(":checkbox,:radio",e.newNode).attr("checked",true);
			e.stopPropagation();
		}
		
		function save(e)
		{
			var that=$(this);
			//console.log(this,that.data("relation"));
			var names=[];
			var ids=[];
			$("thead label",this).each(function(){
				var that=$(this);
				names.push(that.contents().not("[nodeType=1]")[0].nodeValue);
				ids.push($(":checkbox,:radio",this).val());
			});
			that.data("relation").val(names.join(" "));
			that.data("relation").next().val(ids);
			that.trigger("popdown");
			e.stopPropagation();
		}
		
		this.each(function(){
			var that=$(this);
			if(!that.data("isMselector"))
			{
                var filter=that.parents(".popwin").bind("save",save).data("relation").val();
                filter=new RegExp("^(?:"+$.trim(filter).replace(/\s+/g,"|")+")$");
                that.bind("addSelect",addSelect);
				$("tbody span",this).click(popup)
								 // .mouseleave(popdown);
                var labels=$("tbody label",this).click(setSelect).filter(function(){
                        return filter.test($.trim($(this).text()));
                    }).click();
				that.data("isMselector",true);
                $("button",this).bind("click",function(){$(this).trigger("save")});
			}
		});
		return this;

	}
	
	/**
	 * 阻止起泡
	 */
	function xo(e)
	{e.stopPropagation()}
	
	/**
	 * 选择项目时的处理函数
	 */
	function setSelect(e)
	{
		var that=$(this);
		var checker=$(":checkbox,:radio",this);
		if(that.data("rel"))
		{
			setTimeout(function(){checker.attr("checked",false);},0);
			that.data("rel").remove();
			that.removeData("rel");
		}
		else
		{
			setTimeout(function(){checker.attr("checked",true);},0);
			var clone=that.clone();
			//$(":checkbox,:radio",clone).attr("checked",true);
			clone.click(function(){that.trigger("click")});
			var event=new jQuery.Event("addSelect");
			event.newNode=clone;
			that.data("rel",clone);
			that.trigger(event);
		}
		e.preventDefault();
	}
	
	$(".spTab label").live("click",setSelect);
	//$(".spTab :checkbox").live("click",function(e){console.log("test");e.preventDefault();});
	
	//$(".mselector").live("popup",xo)
	//			   .live("popdown",xo);
	
	
	if ( $.browser.msie && $.browser.version == "6.0")
	{
		$(".mselector span,.spTab td").live("mouseover",toggleHover).live("mouseout",toggleHover);
	}
	
})(jQuery);

