/*
* The float div Html structure:
'<div class="e-fdiv-wrap">' +
'  <div class="e-fdiv-top-left"></div>'+
'  <div class="e-fdiv-top-right"><a href="#" title="close" class="e-fdiv-close">close</a></div>'+
'  <div class="e-fdiv-title"></div>'+
'  <div class="e-fdiv-txt-wrap"></div>'+
'  <div class="e-fdiv-bottom-left"></div>'+
'  <div class="e-fdiv-bottom-right"></div><div class="e-fdiv-center"></div>'
'  </div>'
 */
jQuery.fn.extend({
	fdiv:function(opt)
	{
		var me = this,
			elm = jQuery.fn.fdiv;

		opt = this.extend({
				zindex : this.attr('z-index') ? this.attr('z-index') : 1000,
				title:'System Dialog Div',
				width:400,
				height:me.height(),
				minHight:150,
				minWidth:200,
				modal:false,
				overFlow:'auto',
				destroy:false,	//当窗口关闭时是否销毁对话框
				iframeUrl:'',
				position:"center center"
				},opt || {});
			//alert(opt.width);
		var	sid = elm.getTitleId(this),
			title = opt.title || this.attr('title') || '&#160;',
			width = Math.max(opt.width,opt.minWidth),
			height = Math.max(opt.height,opt.minHight);
		me.zindex = opt.zindex + elm.maxZ;
		me.pre_elm = me.prev();//取得当前所在的近邻前一个元素
		me.visibled = me.css('display')== 'none' || me.css('visibility')=='hidden' ? 0 : 1;//alert(this.attr('tagName'));
		
		//存储标签的名称，如果为iframe框架，则根据用户设置自动处理
		//如果是iframe框架，且用户设置了URL参数(iframeUrl) 则，替换框架中的src
		//如果用户不设置框架地址，则只设置框架的宽和高至浮动层相适应
		me.tag = this.attr('tagName') ? this.attr('tagName').toLowerCase() : '';
		if(!me.tag)	return;

		if(!jQuery('#'+sid).length)
		{
			me.Udiv = $('<div></div>').hide().addClass('e-fdiv-wrap')
					.css({'width':width,'height':height,'z-index':me.zindex,'left':0,'top':0})
					.attr('id',sid).appendTo('body');
			me.Udiv_ftl = $('<div></div>').addClass('e-fdiv-top-left').appendTo(me.Udiv);
			me.Udiv_ftr = $('<div></div>').addClass('e-fdiv-top-right').appendTo(me.Udiv);
			me.Udiv_close = $('<a href="#"></a>').addClass('e-fdiv-close').attr('title','close').appendTo(me.Udiv_ftr).click(function(){me.Udiv.close()});
			me.Udiv_title = $('<div></div>')
							.addClass('e-fdiv-title')
							.html(title)
							.css('cursor','move')
							.mousedown(function()
							{
								me.Udiv.draggable({disabled:false});
								var w=jQuery('.e-fdiv-wrap');
								if(w.length>1)
								{
									var mx = opt.zindex;
									w.each(function()
									{
										if($(this).css('z-index')>mx)	mx = $(this).css('z-index');
									});
									jQuery(me.Udiv).css('z-index',parseInt(mx)+1);
								}
							})
							.mouseup(function(){me.Udiv.draggable({disabled:true}).css('opacity',1)})
							.appendTo(me.Udiv)
							.disableSelection();
			me.Udiv_txt = $('<div></div>').addClass('e-fdiv-txt-wrap').css({'height':height-60,width:width-28,'overflow':opt.overFlow}).appendTo(me.Udiv);
			me.elm = this.show().attr('e-fdiv-sign',sid).appendTo(me.Udiv_txt);
			me.Udiv_fbl = $('<div></div>').addClass('e-fdiv-bottom-left').appendTo(me.Udiv);
			me.Udiv_fbr = $('<div></div>').addClass('e-fdiv-bottom-right').appendTo(me.Udiv);
			me.Udiv_fbc = $('<div></div>').addClass('e-fdiv-bottom-center').css({width:width-24,height:5,'overflow':'hidden','position':'absolute','bottom':0,'left':0,background:'#fff'}).appendTo(me.Udiv);
			if(me.tag=='iframe')
			{
				this.css({'height':height-60,width:width-28}).attr({'frameborder':'0','border':0});
				if(opt.iframeUrl)	this.attr('src',opt.iframeUrl);
			}
			elm.maxZ++;
		}
		else
		{
			me.Udiv = $('#'+sid);
			me.Udiv.find('.e-fdiv-title').html(title);
		}
		if(opt.modal)
		{
			me.modal = $('<div></div>')
			.attr('id','e-fdiv-modal-'+sid)
			.css({width:$(window).width(),height:$(window).height(),position:'absolute','z-index':opt.zindex-1,left:0,top:0,background:'#000','opacity':0.2})
			.appendTo('body');
			
		}
		me.Udiv.show();
		elm._position(this.Udiv,opt.position);
		
		$(window).resize(function(){elm._position(this.Udiv,opt.position);$('#e-fdiv-modal-'+sid).css({width:$(window).width()});});
		me.Udiv.close = function()
		{
			$(this).hide();
			if(opt.modal)	me.modal.remove();
			if(opt.destroy)
			{
				me.attr('e-fdiv-sign','');
				if(me.pre_elm)	me.pre_elm.after(me);
				else	me.appendTo('body');
				me.Udiv.remove();
				if(!me.visibled)	me.css('display','none');
				if(me.tag=='iframe' && opt.iframeUrl)	me.attr('src','');
			}
		}
		return this;
	},
	
	loading:function(opt)
	{
		opt = this.extend({
			img:(site_root?site_root+'stuff/img/default/loading.gif':''),
			text:'Loading...',
			timeout:0
			},opt || {});
		var lobj = $('<div></div>').hide().css({"z-index":1000,position:"relative",'text-align':'center',width:$(this).width(),height:$(this).height(),'line-height':$(this).height()})
			.html('<img src="'+opt.img+'" border="0" align="absmiddle" /> '+opt.text)
			.show()
			.appendTo(this);
		if(opt.timeout)
		{
			var me = this;
			setTimeout(function(){lobj.remove()},opt.timeout);
		}
		return this;
	},
	
	slide:function(opt)
	{
		opt = this.extend({
			timeout:3000,
			effect:'default',
			show_menu:true,
			show_arrow:false,
			debug:0
			},opt || {});
		this.current = 0;
		this.first = 1;
		this.direction = 'right';//left or right
		var li = $(this).find('ul>li'),
			len = li.length - 1,
			menu = '',
			sid = $(this).attr('id');
			me = this,
			j = 1;
		if($.inArray($(me).css('position'),['absolute','relative','fixed'])==-1)	$(me).css('position','relative');
		if($(me).css('overflow')!='hidden')	$(me).css('overflow','hidden');

		li.each(function(i,n)
		{
			var img = $(this).find('img');
			if(img.length<1)
			{
				len--;
				j--;
				$(this).remove();
				return true;
			}
			else	img.mouseover(function(){clearInterval(me.timer);}).mouseout(function(){me._switch();});
			
			$(this).attr('id',sid+'_pic_'+i).css({'position':'absolute','overflow':'hidden'});
			menu += '<li id="'+(sid+'_menu_'+i)+'">'+j+'</li>';
			j++;
		});
		me.Smenu = $('<ol></ol>').hide().css({'opacity':0.7,'z-index':15}).html(menu).appendTo(me);
		me.Smenu.find('li').each(function(i,n)
		{
			if(i==0)	$(this).addClass('active');
			$(this).css('cursor','pointer').mouseover(function(){clearInterval(me.timer);me.current = i;me.timero=setTimeout(function(){me._show()},300);});
			$(this).mouseout(function(){me._switch();clearInterval(me.timero);});
		});
		if(opt.show_menu)	me.Smenu.show();
		
		if(opt.debug)
		{
			$('<div></div>').attr('id',sid+'__test').css({'opacity':0.6,padding:'0 5px',top:0,left:0,height:30,'line-height':'30px','background':'#000','color':'#0f0',position:'absolute'}).appendTo(me);
		}
		
		if(opt.show_arrow)
		{
			var mh = $(me).height(),
				mw = $(me).width(),
				css = {'position':'absolute','width':50,height:mh,top:0,'font':'bold 72px/'+mh+'px 黑体,宋体','color':'#444','background':'#fff','opacity':'0.5','cursor':'pointer','z-index':10},
				larrow = $('<div></div>').css('left',0).css(css).html('&lt;').hide()
				.mouseover(function(){$(this).css('opacity','0.7');clearInterval(me.timer);})
				.mouseout(function(){$(this).css('opacity','0.5');me.direction='right';me._switch();})
				.click(function()
				{
					clearInterval(me.timer);
					if(me.direction=='right')
					{
						me.current -= 2;
						me.direction = 'left';
					}
					me._show()
				})
				.appendTo(me),
				
				rarrow = $('<div></div>').css({'right':0,'text-align':'right'}).css(css).html('&gt;').hide()
				.mouseover(function(){$(this).css('opacity','0.7');clearInterval(me.timer); })
				.mouseout(function(){$(this).css('opacity','0.5');me.direction='right';me._switch();})
				.click(function()
				{
					clearInterval(me.timer);
					if(me.direction=='left')
					{
						me.direction = 'right';
						me.current += 2; 
					}
					me._show();
				})
				.appendTo(me);
			$(me).mouseover(function(){larrow.show();rarrow.show();}).mouseout(function(){larrow.hide();rarrow.hide();});
		}
		
		this._switch = function()
		{
			me.timer = setInterval(function(){me._show()},opt.timeout);
		}
		
		this._show = function()
		{
			if(me.first)
			{
				me.current = 1;
				me.first = 0;
			}
			me.current = me.current || 0;
			if(me.current > len) me.current = 0;
			if(me.current < 0)	me.current = len;
			
			var w = $(me).find('#'+sid+'_pic_'+me.current).width(),
				h = $(me).find('#'+sid+'_pic_'+me.current).height(),
				_effect = opt.effect;
			
			if(opt.effect=='default')
			{
				var effect_arr = ['LTslide','RTslide','LBslide','RBslide','LXslide','RXslide','YTslide','YBslide','fade','explode'],
					cur = me._random(0,effect_arr.length-1);
				_effect = effect_arr[cur];
			}
			if(opt.debug)	$('#'+sid+'__test').html('No.'+(cur+1)+', Effect:'+_effect);
			
			switch(_effect)
			{
				case 'LTslide'://left top
				case 'RTslide'://right top
				case 'LBslide'://left bottom
				case 'RBslide'://right bottom
				case 'LXslide'://left x
				case 'RXslide':// right x
				case 'YTslide'://y top
				case 'YBslide'://y bottom
					var x = _effect.substr(0,1),
						y = _effect.substr(1,1),
						yx = y == 'X' ? 0 : h*-1,
						xx = x =='Y' ? 0 : w*-1;
					x = x=='L' ? 'left':'right';
					y = y=='B' ? 'bottom':'top';
					var _x = x=='left' ? 'right':'left',
						_y = y=='top' ? 'bottom':'top';
					eval("oh={"+y+":'"+yx+"',"+x+":'"+xx+"',opacity:'hide'}");
					eval("os={"+y+":0,"+x+":0,opacity:'show'}");
					//eval('_os={'+x+':"0",'+y+':"0"}');
					$(me).find('ul li:visible').animate(oh,{duration: 800});
					$(me).find('#'+sid+'_pic_'+me.current).attr('style','position:absolute;overflow:hidden;display:none;'+y+':'+(-1*yx)+'px;'+x+':'+(-1*xx)+'px;').animate(os,{duration: 500 ,complete:function(){/* $(me).find('li:hidden').attr('style','').hide(); */}});
				break;
				
				case 'fade':
				default:
					$(me).find('ul li:visible').fadeOut('slow');
					$(me).find('#'+sid+'_pic_'+me.current).attr('style','display:none').fadeIn('slow');
				break;
			}
			$(me).find('ol li[class="active"]').removeClass('active');
			$(me).find('#'+sid+'_menu_'+me.current).addClass('active');
			if(me.direction=='right')	me.current++;
			else me.current--;
		}
		
		this._random = function(start, end)
		{
    		return Math.round(Math.random() * (end - start) + start);
    	}
		me._switch();
		return this;
	},
	_tags:function()
	{
		var me = this;
		this.tag = function(num)
		{
			num = num || 0;
			$(this).find('a').each(function(i,n)
			{
				var id = $(this).attr('href');
				$(id).css('display',(num==i?'':'none'));
				if(i==num) $(this).addClass('active');
				else $(this).removeClass('active');
			});
		}
		$(this).find('a').each(function(i,n){$(this).mouseover(function(){me.tag(i)})});
		me.tag(0);
		return this;
	},
	query_str:function(opt)
	{
		var str = '';
		opt = this.extend({
			_select:true,
			_input:true,
			_textarea:true
			},opt || {});
		var me = this;
		this.set_str = function(key,val)
		{
			if(!key)	return;
			return '&' + key + '=' + encodeURIComponent(val);
		}
		
		this.get_str = function(type)
		{
			$(this).find(type).each(function()
			 {
				if(!$(this).attr('name'))	return true;
				str += me.set_str($(this).attr('name'), $(this).val());
			 });
			return str;
		}
		
		$.each(['_select','_input','_textarea'],function(i,n)
		{
			if(opt[n])	me.get_str(n.substr(1));
		});
		return str.substr(1);
	},
	td_alt:function(opt)
	{
		opt = this.extend({
				class_name:"alt"
				},opt || {});
		
		$(this).find('td:even').each(function(){$(this).addClass(opt.class_name);});
		return this;
	},
	tr_alt:function(opt)
	{
		opt = this.extend({
				class_name:"active"
				},opt || {});
		
		$(this).find('tr').each(function(){$(this).mouseover(function(){$(this).addClass(opt.class_name);}).mouseout(function(){$(this).removeClass(opt.class_name)})});
		return this;
	}
}); 
jQuery.extend(jQuery.fn.fdiv,
{
	uuid : 0,
	maxZ : 0,
	getTitleId : function($el)
	{
		if($el.attr('e-fdiv-sign'))	return $el.attr('e-fdiv-sign');
		var id = $el.attr('id') ? $el.attr('id') : '';
		if (!id)
		{
			this.uuid += 1;
			id = this.uuid;
		}
		return 'fdiv-wrap-' + id;
	},
	_position : function($el,position)
	{
		var myAt = [],
		offset = [0, 0],
		isVisible;
		position = position || jQuery.ui.dialog.prototype.options.position;

		if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) {
			myAt = position.split ? position.split(' ') : [position[0], position[1]];
			if (myAt.length === 1) {
				myAt[1] = myAt[0];
			}

			$.each(['left', 'top'], function(i, offsetPosition) {
				if (+myAt[i] === myAt[i]) {
					offset[i] = myAt[i];
					myAt[i] = offsetPosition;
				}
			});
		} else if (typeof position === 'object') {
			if ('left' in position) {
				myAt[0] = 'left';
				offset[0] = position.left;
			} else if ('right' in position) {
				myAt[0] = 'right';
				offset[0] = -position.right;
			}

			if ('top' in position) {
				myAt[1] = 'top';
				offset[1] = position.top;
			} else if ('bottom' in position) {
				myAt[1] = 'bottom';
				offset[1] = -position.bottom;
			}
		}

		isVisible = $el.is(':visible');
		if (!isVisible) {
			$el.show();
		}
		$el.css({ top: 0, left: 0 })
			.position({
				my: myAt.join(' '),
				at: myAt.join(' '),
				offset: offset.join(' '),
				of: window,
				collision: 'fit',
				// ensure that the titlebar is never outside the document
				using: function(pos) {
					var topOffset = $(this).css(pos).offset().top;
					if (topOffset < 0) {
						$(this).css('top', pos.top - topOffset);
					}
				}
			});
		if (!isVisible) {
			$el.hide();
		}
	}
});

