jQuery.fn.extend({
	loading:function(opt)
	{
		opt = this.extend({
			img:(site_root?site_root+'stuff/img/default/loading.gif':''),
			text:'Loading...',
			timeout:0
			},opt || {});
		if($(this).css('position')=='static')	$(this).css('position','relative');
		var lobj = $('<div></div>')
			.hide()
			.css({
				"z-index":1000000,
				position:"absolute",
				'text-align':'center',
				width:$(this).width(),
				height:$(this).height(),
				'line-height':$(this).height() + 'px',
				top:0,
				left:0
			})
			.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 lobj;
	},
	
	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(opt)
	{
		var me = this;
		opt = this.extend({
			class_name:'active',
			show:'',
			event:'mouseover'
			},opt || {});
		k = 0;
		this.tag = function(num)
		{
			num = num || 0;
			$(this).find('a').each(function(i,n)
			{
				var id = $(this).attr('href');
				var cond = num==i || '#'+num==id;
				$(id).css('display',(cond?'':'none'));
				if(cond) $(this).addClass(opt.class_name);
				else $(this).removeClass(opt.class_name);
			});
		};
		$(this).find('a').each(function(i,n){$(this).bind(opt.event,function(){me.tag(i);return false;})});
		me.tag(opt.show);
		return this;
	},
		
	query_str:function(opt)
	{
		var str = '';
		opt = this.extend({element:'input,select,textarea'},opt || {});
		var me = this;
		$(this).find(opt.element).each(function() {
			if($(this).attr('tagName').toLowerCase()=='input' && 
				$.inArray($(this).attr('type'),['checkbox','radio'])!=-1 && 
				!$(this).attr('checked')
			)	return true;
			var name = $(this).attr('name'),
				val = $(this).val();
			if(!name)	return true;
			str += '&'+name+'='+encodeURIComponent(val);
		});
		return str.substr(1);
	},
		
	td_alt:function(opt)
	{
		opt = this.extend({
				class_name:"alt"
				},opt || {});
		
		$(this).find('td:even').addClass(opt.class_name);
		return this;
	},
	tr_alt:function(opt)
	{
		opt = this.extend({
				class_name:"active"
				},opt || {});
		
		$(this).find('tr').mouseover(function(){$(this).addClass(opt.class_name);}).mouseout(function(){$(this).removeClass(opt.class_name)});
		return this;
	},
	xy:function()
	{
		//e = e || window.event;
		var body_width = $(document.body).width(),
			body_height = Math.max($(document.body).height(),$(window).height()),
			width = $(this).width() + $(this)._border(1) + $(this)._padding(1),
			height = $(this).height() + $(this)._border() + $(this)._padding(),
			me = this,
			x,y,ox,oy;
		
		$(document).ready(function(){
			$(document.body).mousemove(function(event)
			{
				x = event.pageX || event.originalEvent.x || event.originalEvent.layerX || 0;
				ox = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || window.scrollX || 0;
			    y = event.pageY || event.originalEvent.y || event.originalEvent.layerY || 0;
			    oy = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || window.scrollY || 0;

			    _left = x+width+5 > body_width ? x-width-5 : x+5;
			    if(_left<0)	_left = ox; 
			    _top = y+height+5 > body_height ? y-height-5 : y+5;//window.document.title= y+height+5+' '+body_height+' window h:'+$(window).height()+' body h:'+$('body').height();
			    if(_top<0)	_top = 0;
				$(me).css({position:'absolute',left:_left,top:_top,'z-index':9999});
		    } );
		});
	},
	_border:function(is_width)
	{
		if(is_width)	return parseInt($(this).css('border'))*2 || (parseInt($(this).css('border-left-width'))||0)+(parseInt($(this).css('border-right-width'))||0) || parseInt($(this).attr('border')) || 0;
		return parseInt($(this).css('border'))*2 || (parseInt($(this).css('border-top-width'))||0)+(parseInt($(this).css('border-bottom-width'))||0) || parseInt($(this).attr('border')) || 0;
	},
	_padding:function(is_width)
	{
		if(is_width)	return parseInt($(this).css('padding'))*2 || parseInt($(this).css('padding-left'))+parseInt($(this).css('padding-right')) || 0;
		return parseInt($(this).css('padding'))*2 || parseInt($(this).css('padding-top'))+parseInt($(this).css('padding-bottom')) || 0;
	},
	preview:function(opt)
	{
		opt = this.extend({width:400,type:'image',source:'src',e:window.event},opt || {});
		var self = this;
		return $(this).each(function()
		{
			$(this).mouseover(function(event)
			{
				var elm = $.trim($(this).attr(opt.source));
				if(!elm)	return;
				var wrap = $('#ezool_preview');
				var me = this;
				
				if(wrap.length<1)
				{
					wrap = $('<div/>').attr('id','ezool_preview').css({'overflow':'hidden','text-align':'left','line-height':'18px','background':'#999','border':'1px solid #333','padding':'5px','float':'left'}).appendTo('body');
					if(opt.type=='image')
					{
						var oimg = $('<img/>').attr('src',elm).css('border','none').hide().appendTo(wrap);
						var loading = $('<img/>').attr('src',site_root+'stuff/img/default/loading.gif').css({border:'none'}).appendTo(wrap);
						var img = new Image();
						img.src = elm;
						var resize = function()
						{
							var imgw = img.width,
								imgh = img.height;
							if(imgw>opt.width)
							{
								if(imgw>imgh)
								{
									imgh = parseInt(opt.width/imgw * imgh);
									imgw = opt.width;
								}
								else
								{
									imgw = parseInt(opt.width/imgh * imgw);
									imgh = opt.width;
								}
							}
							else if(imgh>opt.width)
							{
								imgw = parseInt(opt.width/imgh * imgw);
								imgh = opt.width;
							}
							oimg.width(imgw).height(imgh).attr('src','');
						},
						imgload = function()
						{
							resize();
							loading.remove();
							var txt = $(me).attr('tip') || $(me).attr('alt') || $(me).attr('title');
							if(txt)	$('<p/>').css({margin:0,padding:'5px 0 0',color:'#fff'}).html(txt).appendTo(wrap);
							oimg.attr('src',elm).show();
							wrap.width(oimg.width()||opt.width).xy();
						};
						if(img.complete)
						{
							imgload(img);
						}
						else $(img).load(function(){imgload(img);})
						$(img).error(function(){oimg.remove();loading.remove();});
					}
					else
					{
						$('<p/>').css({margin:0,padding:0}).html(elm).appendTo(wrap);
						wrap.width(opt.width).xy(event);
					}
				}
				else wrap.xy(event);
			})
			.mouseout(function(){$('#ezool_preview').remove()});
		});
	},
	fixPNG : function() {
		return this.find('*').each(function () {
			var image = $(this).css('backgroundImage');
			if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
				image = RegExp.$1;
				$(this).css({
					'backgroundImage': 'none',
					'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + ($(this).css('backgroundRepeat') == 'no-repeat' ? 'crop' : 'scale') + ", src='" + image + "')"
				})
				.each(function () {
					var position = $(this).css('position');
					if (position != 'absolute' && position != 'relative'){
						$(this).css('position', 'relative');
					}
				});
			}
		})
	}
}); 


/*
 * jQuery UI Dialog 1.8.7
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *  jquery.ui.button.js
 *	jquery.ui.draggable.js
 *	jquery.ui.mouse.js
 *	jquery.ui.position.js
 *	jquery.ui.resizable.js
 */
(function( $, undefined ) {

var uiDialogClasses =
		'e-fdiv-wrap ',
		//'ui-widget ' +
		//'ui-widget-content ' +
		//'ui-corner-all ',
	cssWidth = 'ez-fdiv-width',
	cssHeight = 'ez-fdiv-height',
	sizeRelatedOptions = {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},
	resizableRelatedOptions = {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	};

$.widget("ez.fdiv", {
	options: {
		autoOpen: true,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		dialogClass: '',
		draggable: true,
		hide: null,
		height: 'auto',
		maxHeight: false,
		maxWidth: false,
		minHeight: 100,
		minWidth: 150,
		modal: false,
		position: {
			my: 'center',
			at: 'center',
			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);
				}
			}
		},
		resizable: true,
		show: null,
		stack: true,
		title: '',
		width: 300,
		zIndex: 1000,
		theme: 'azury',
		iframeUrl:'',
		isIframe: false
	},

	_create: function() {
		this.originalTitle = this.element.attr('title');
		// #5742 - .attr() might return a DOMElement
		if ( typeof this.originalTitle !== "string" ) {
			this.originalTitle = "";
		}
		if ( !this.options.title && ( this.options.theme=='azury' || this.options.theme=='blue'))
		{
			this.options.theme = 'default';
		}
		this.options.isIframe = this.options.iframeUrl && this.element.attr('tagName').toLowerCase()=='iframe';

		this.options.title = this.options.title || this.originalTitle;
		var self = this,
			options = self.options,
			theme = '-' + options.theme,

			title = options.title || '',
			titleId = $.ez.fdiv.getTitleId(self.element),

			uiDialog = (self.uiDialog = $('<div></div>'))
				.appendTo(document.body)
				.hide()
				.addClass(uiDialogClasses + options.dialogClass)
				.css({
					position: 'absolute',
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
					if (options.closeOnEscape && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE) {
						
						self.close(event);
						event.preventDefault();
					}
				})
				.attr({
					role: 'fdiv',
					'aria-labelledby': titleId
				})
				.mousedown(function(event) {
					self.moveToTop(false, event);
				}),
			
			uiDialogTitlebarClose = $('<a href="#"/>')
				.addClass(
					'fdiv-close' +
					(theme?' fdiv-close'+theme:'')
				)
				.attr({'role':'button','title':options.closeText})
				.css('zIndex',options.zIndex+1)
				.click(function(event) {
					self.close(event);
					return false;
				})
				.appendTo(uiDialog),
				
			uiDialogTable = (this.uiDialogTable = $('<table/>')).attr({
					cellspacing:0,
					cellpadding:0,
					border:0,
					width:'100%',
					height:'100%',
					valign:'top'
				})
				.appendTo(uiDialog),
				
			uiDialogTopTr = (this.uiDialogTopTr = $('<tr/>'))
				.addClass('fdiv-ttr'+(theme?' fdiv-ttr'+theme:''))
				.html('<td class="fdiv-tltd' + (theme?' fdiv-tltd'+theme:'') + ' ' + cssWidth + ' '+ cssHeight+'"></td>' +
					 '<td class="fdiv-tmtd'+(theme?' fdiv-tmtd'+theme:'')+' '+ cssHeight+'"></td>' +
					 '<td class="fdiv-trtd'+(theme?' fdiv-trtd'+theme:'') + ' ' + cssWidth +' '+ cssHeight+ '"></td>')
				.appendTo(uiDialogTable),
			
			mtr = $('<tr/>')
				.attr('valign','top')
				.addClass('fdiv-mtr'+(theme?' fdiv-mtr'+theme:''))
				.appendTo(uiDialogTable),
			
			mtd = $('<td/>').addClass('fdiv-mltd'+(theme?' fdiv-mltd'+theme:'')+ ' ' + cssWidth).appendTo(mtr),

			uiDialogContentWrap = $('<td/>')
				.addClass(
					'fdiv-mmtd' + 
					' ez-fdiv-content' +
					(theme?' fdiv-mmtd'+theme:''))
				.appendTo(mtr),
			
			uiDialogContentWrapDiv = $('<div/>')
				.css({
					'overflow-y':'auto',
					'overflow-x':'hidden'
				})
				.appendTo(uiDialogContentWrap),

			uiDialogContent = this.element
				.show()
				.removeAttr('title')
				.addClass('fdiv-text-wrap')
				.appendTo(uiDialogContentWrapDiv),
			
			mtd = $('<td/>')
				.addClass('fdiv-mrtd'+(theme?' fdiv-mrtd'+theme:'') + ' ' + cssWidth)
				.appendTo(mtr),
				
			uiDialogBtr = (this.uiDialogBtr = $('<tr/>'))
				.addClass('fdiv-btr'+(theme?' fdiv-btr'+theme:''))
				.html('<td class="fdiv-bltd' + (theme?' fdiv-bltd'+theme:'') +  ' ' + cssWidth +' ' + cssHeight +'"></td>' +
					  '<td class="fdiv-bmtd' + (theme?' fdiv-bmtd'+theme:'') + ' ' + cssHeight + '"></td>' +
					  '<td class="fdiv-brtd' + (theme?' fdiv-brtd'+theme:'') +  ' ' + cssWidth +' ' + cssHeight +'"></td>')
				.appendTo(uiDialogTable);
			
			if(title)
			{
				var uiDialogTitlebar = (this.uiDialogTitlebar = $('<tr/>'))
					.addClass(
						'ez-fdiv-title' + 
						' ez-fdiv-titlebar' + 
						(theme?' ez-fdiv-title'+theme:'')
					),
				
				uiDialogTitlebarLtd = $('<td/>').addClass('fdiv-title-ltd'+(theme?' fdiv-title-ltd'+theme:'')).appendTo(uiDialogTitlebar),
				uiDialogTitlebarMtd = $('<td/>').addClass('fdiv-title-mtd'+(theme?' fdiv-title-mtd'+theme:'')).appendTo(uiDialogTitlebar),
				uiDialogTitlebarRtd = $('<td/>').addClass('fdiv-title-rtd'+(theme?' fdiv-title-rtd'+theme:'')).appendTo(uiDialogTitlebar),
				uiDialogTitle = $('<strong/>')
					.addClass('ez-fdiv-title')
					.attr('id', titleId)
					.html(title)
					.appendTo(uiDialogTitlebarMtd);
				uiDialogTopTr.after(uiDialogTitlebar);
			}
			
			if(options.isIframe)
			{
				this.element.attr('src',options.iframeUrl);
			}

		//handling of deprecated beforeclose (vs beforeClose) option
		//Ticket #4669 http://dev.jqueryui.com/ticket/4669
		//TODO: remove in 1.9pre
		if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) {
			options.beforeClose = options.beforeclose;
		}

		if(options.title && uiDialogTitlebar)	uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		if (options.draggable && $.fn.draggable) {
			self._makeDraggable();
		}
		if (options.resizable && $.fn.resizable) {
			self._makeResizable();
		}

		self._createButtons(options.buttons);
		self._isOpen = false;

		if ($.fn.bgiframe) {
			uiDialog.bgiframe();
		}
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
		if(this.options.theme)
		{
			this._setTheme(this.options.theme);
		}
	},

	destroy: function() {
		var self = this;
		
		if (self.overlay) {
			self.overlay.destroy();
		}
		self.uiDialog.hide();
		self.element
			.unbind('.fdiv')
			.removeData('fdiv')
			.removeClass('ez-fdiv-content')
			.hide().appendTo('body');
		self.uiDialog.remove();

		if (self.originalTitle) {
			self.element.attr('title', self.originalTitle);
		}

		return self;
	},

	widget: function() {
		return this.uiDialog;
	},

	close: function(event) {
		var self = this,
			maxZ, thisZ;
		
		if (false === self._trigger('beforeClose', event)) {
			return;
		}

		if (self.overlay) {
			self.overlay.destroy();
		}
		self.uiDialog.unbind('keypress.ez-fdiv');

		self._isOpen = false;

		if (self.options.hide) {
			self.uiDialog.hide(self.options.hide, function() {
				self._trigger('close', event);
			});
		} else {
			self.uiDialog.hide();
			self._trigger('close', event);
		}

		$.ez.fdiv.overlay.resize();

		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		if (self.options.modal) {
			maxZ = 0;
			$('.ez-fdiv').each(function() {
				if (this !== self.uiDialog[0]) {
					thisZ = $(this).css('z-index');
					if(!isNaN(thisZ)) {
						maxZ = Math.max(maxZ, thisZ);
					}
				}
			});
			$.ez.fdiv.maxZ = maxZ;
		}

		return self;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force, event) {
		var self = this,
			options = self.options,
			saveScroll;

		if ((options.modal && !force) ||
			(!options.stack && !options.modal)) {
			return self._trigger('focus', event);
		}

		if (options.zIndex > $.ez.fdiv.maxZ) {
			$.ez.fdiv.maxZ = options.zIndex;
		}
		if (self.overlay) {
			$.ez.fdiv.maxZ += 1;
			self.overlay.$el.css('z-index', $.ez.fdiv.overlay.maxZ = $.ez.fdiv.maxZ);
		}

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		saveScroll = { scrollTop: self.element.attr('scrollTop'), scrollLeft: self.element.attr('scrollLeft') };
		$.ez.fdiv.maxZ += 1;
		self.uiDialog.css('z-index', $.ez.fdiv.maxZ);
		self.element.attr(saveScroll);
		self._trigger('focus', event);

		return self;
	},

	open: function() {
		if (this._isOpen) { return; }

		var self = this,
			options = self.options,
			uiDialog = self.uiDialog;

		self.overlay = options.modal ? new $.ez.fdiv.overlay(self) : null;
		self._size();
		self._position(options.position);
		uiDialog.show(options.show);
		self.moveToTop(true);

		// prevent tabbing out of modal dialogs
		if (options.modal) {
			uiDialog.bind('keypress.ez-fdiv', function(event) {
				if (event.keyCode !== $.ui.keyCode.TAB) {
					return;
				}

				var tabbables = $(':tabbable', this),
					first = tabbables.filter(':first'),
					last  = tabbables.filter(':last');

				if (event.target === last[0] && !event.shiftKey) {
					first.focus(1);
					return false;
				} else if (event.target === first[0] && event.shiftKey) {
					last.focus(1);
					return false;
				}
			});
		}

		// set focus to the first tabbable element in the content area or the first button
		// if there are no tabbable elements, set focus on the dialog itself
		$(self.element.find(':tabbable').get().concat(
			uiDialog.find('.ez-fdiv-buttonpane :tabbable').get().concat(
				uiDialog.get()))).eq(0).focus();

		self._isOpen = true;
		self._trigger('open');

		return self;
	},

	_createButtons: function(buttons) {
		var self = this,
			theme = '-' + this.options.theme,
			hasButtons = false,
			uiDialogButtonPane = $('<tr/>')
				.addClass(
					'ez-fdiv-buttonpane ' +
					'fdiv-btntr' + 
					(theme?' fdiv-btntr'+theme:'')
				);

		// if we already have a button pane, remove it
		self.uiDialog.find('.ez-fdiv-buttonpane').remove();
		
		$('<td/>').addClass('fdiv-btnltd'+(theme?' fdiv-btnltd'+theme:'')).appendTo(uiDialogButtonPane);
		var uiDialogButtonWrap = $('<td/>').addClass('fdiv-btnmtd'+(theme?' fdiv-btnmtd'+theme:'')).appendTo(uiDialogButtonPane);

		if (typeof buttons === 'object' && buttons !== null) {
			$.each(buttons, function() {
				return !(hasButtons = true);
			});
		}
		if (hasButtons) {
			$.each(buttons, function(name, props) {
				props = $.isFunction( props ) ?
					{ click: props, title: name } :
					props;
				var button = $('<span/>')
					.addClass('fdiv-button')
					.html('<span>'+name+'</span>')
					.attr( props, true )
					.unbind('click')
					.click(function() {
						props.click.apply(self.element[0], arguments);
					})
					.mouseover(
						function() {
							$(this).addClass('fdiv-button-active');
						}
					)
					.mouseout(function() {
						$(this).removeClass('fdiv-button-active');
					})
					.appendTo(uiDialogButtonWrap);
/*				if ($.fn.button) {
					button.button();
				}*/
			});
			$('<td/>').addClass('fdiv-btnrtd'+(theme?' fdiv-btnrtd'+theme:'')).appendTo(uiDialogButtonPane);
			this.uiDialogBtr.before(uiDialogButtonPane);
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = self.options,
			doc = $(document),
			heightBeforeDrag;

		function filteredUi(ui) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		self.uiDialog.draggable({
			cancel: '.ez-fdiv-content, .ez-fdiv-titlebar-close',
			handle: '.ez-fdiv-titlebar',
			containment: 'document',
			start: function(event, ui) {
				heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height();
				$(this).height($(this).height()).addClass("ez-fdiv-dragging");
				self._trigger('dragStart', event, filteredUi(ui));
			},
			drag: function(event, ui) {
				self._trigger('drag', event, filteredUi(ui));
			},
			stop: function(event, ui) {
				options.position = [ui.position.left - doc.scrollLeft(),
					ui.position.top - doc.scrollTop()];
				$(this).removeClass("ez-fdiv-dragging").height(heightBeforeDrag);
				self._trigger('dragStop', event, filteredUi(ui));
				$.ez.fdiv.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = self.options,
			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = self.uiDialog.css('position'),
			resizeHandles = (typeof handles === 'string' ?
				handles	:
				'n,e,s,w,se,sw,ne,nw'
			);

		function filteredUi(ui) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		self.uiDialog.resizable({
			cancel: '.ez-fdiv-content',
			containment: 'document',
			alsoResize: self.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: self._minHeight(),
			handles: resizeHandles,
			start: function(event, ui) {
				$(this).addClass("ez-fdiv-resizing");
				self._trigger('resizeStart', event, filteredUi(ui));
			},
			resize: function(event, ui) {
				self._trigger('resize', event, filteredUi(ui));
			},
			stop: function(event, ui) {
				$(this).removeClass("ez-fdiv-resizing");
				options.height = $(this).height();
				options.width = $(this).width();
				self._trigger('resizeStop', event, filteredUi(ui));
				$.ez.fdiv.overlay.resize();
			}
		})
		.css('position', position)
		.find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se ez-fdiv-resizable');
	},

	_minHeight: function() {
		var options = this.options;

		if (options.height === 'auto') {
			return options.minHeight;
		} else {
			return Math.min(options.minHeight, options.height);
		}
	},

	_position: function(position) {
		var myAt = [],
			offset = [0, 0],
			isVisible;

		if (position) {
			// deep extending converts arrays to objects in jQuery <= 1.3.2 :-(
	//		if (typeof position == 'string' || $.isArray(position)) {
	//			myAt = $.isArray(position) ? position : position.split(' ');

			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;
					}
				});

				position = {
					my: myAt.join(" "),
					at: myAt.join(" "),
					offset: offset.join(" ")
				};
			} 

			position = $.extend({}, $.ez.fdiv.prototype.options.position, position);
		} else {
			position = $.ez.fdiv.prototype.options.position;
		}

		// need to show the dialog to get the actual offset in the position plugin
		isVisible = this.uiDialog.is(':visible');
		if (!isVisible) {
			this.uiDialog.show();
		}
		this.uiDialog
			// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
			.css({ top: 0, left: 0 })
			.position($.extend({ of: window }, position));
		if (!isVisible) {
			this.uiDialog.hide();
		}
	},
	
	_setTheme: function(theme)
	{
		switch(theme)
		{
			case 'ie6':
				skin = {padding:5,width:9,height:9,title_height:26};
			break;
			case 'azury':
				skin = {padding:5,width:9,height:9,title_height:30};
			break;
			case 'blue':
				skin = {padding:5,width:4,height:9,title_height:26};
				//opt.fixpng = false;
			break;
			case 'white':
			case 'black':
			case 'double':
			default:
				skin = {padding:5,width:20,height:20,title_height:30};
			break;
		}
		this.uiDialog.find('.'+cssWidth).css({width:skin.width+'px'});
		this.uiDialog.find('.'+cssHeight).css({height:skin.height+'px'});
		this.uiDialog.find('.ez-fdiv-title').find('td').css('height',skin.title_height+'px');
		this.uiDialog.find('.fdiv-text-wrap').css('padding',skin.padding+'px');
		if(this.options.isIframe)
		{
			this.element.css({
				width:(this.options.width - skin.width * 2 - skin.padding * 2),
				height:(this.options.height - skin.height * 2 - skin.padding * 2)
			});
		}
		if($.browser.msie)	this.uiDialog.fixPNG();
	},

	_setOptions: function( options ) {
		var self = this,
			resizableOptions = {},
			resize = false;

		$.each( options, function( key, value ) {
			self._setOption( key, value );
			
			if ( key in sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		});

		if ( resize ) {
			this._size();
		}
		if ( this.uiDialog.is( ":data(resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function(key, value){
		var self = this,
			uiDialog = self.uiDialog;

		switch (key) {
			//handling of deprecated beforeclose (vs beforeClose) option
			//Ticket #4669 http://dev.jqueryui.com/ticket/4669
			//TODO: remove in 1.9pre
			case "beforeclose":
				key = "beforeClose";
				break;
			case "buttons":
				self._createButtons(value);
				break;
			case "closeText":
				// ensure that we always pass a string
				self.uiDialogTitlebarCloseText.text("" + value);
				break;
			case "dialogClass":
				uiDialog
					.removeClass(self.options.dialogClass)
					.addClass(uiDialogClasses + value);
				break;
			case "disabled":
				if (value) {
					uiDialog.addClass('ez-fdiv-disabled');
				} else {
					uiDialog.removeClass('ez-fdiv-disabled');
				}
				break;
			case "draggable":
				var isDraggable = uiDialog.is( ":data(draggable)" );
				if ( isDraggable && !value ) {
					uiDialog.draggable( "destroy" );
				}
				
				if ( !isDraggable && value ) {
					self._makeDraggable();
				}
				break;
			case "position":
				self._position(value);
				break;
			case "resizable":
				// currently resizable, becoming non-resizable
				var isResizable = uiDialog.is( ":data(resizable)" );
				if (isResizable && !value) {
					uiDialog.resizable('destroy');
				}

				// currently resizable, changing handles
				if (isResizable && typeof value === 'string') {
					uiDialog.resizable('option', 'handles', value);
				}

				// currently non-resizable, becoming resizable
				if (!isResizable && value !== false) {
					self._makeResizable(value);
				}
				break;
			case "title":
				// convert whatever was passed in o a string, for html() to not throw up
				$(".ez-fdiv-title", self.uiDialogTitlebar).html("" + (value || '&#160;'));
				break;
			case 'theme':
				self._setTheme(value);
				break;
		}

		$.Widget.prototype._setOption.apply(self, arguments);
	},

	_size: function() {
		/* If the user has resized the dialog, the .ez-fdiv and .ez-fdiv-content
		 * divs will both have width and height set, so we need to reset them
		 */
		var options = this.options,
			nonContentHeight,
			minContentHeight,
			isVisible = this.uiDialog.is( ":visible" );

		// reset content sizing
		this.element.show().css({
			width: 'auto',
			minHeight: 0,
			height: 0
		});

		if (options.minWidth > options.width) {
			options.width = options.minWidth;
		}

		// reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css({
				height: 'auto',
				width: options.width
			})
			.height();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		
		if ( options.height === "auto" ) {
			// only needed for IE6 support
			if ( $.support.minHeight ) {
				this.element.css({
					minHeight: minContentHeight,
					height: "auto"
				});
			} else {
				this.uiDialog.show();
				var autoHeight = this.element.css( "height", "auto" ).height();
				if ( !isVisible ) {
					this.uiDialog.hide();
				}
				this.element.height( Math.max( autoHeight, minContentHeight ) );
			}
		} else {
			this.element.height( Math.max( options.height - nonContentHeight, 0 ) );
		}

		if (this.uiDialog.is(':data(resizable)')) {
			this.uiDialog.resizable('option', 'minHeight', this._minHeight());
		}
	}
});

$.extend($.ez.fdiv, {
	version: "1.8.7",

	uuid: 0,
	maxZ: 0,

	getTitleId: function($el) {
		var id = $el.attr('id');
		if (!id) {
			this.uuid += 1;
			id = this.uuid;
		}
		return 'ez-fdiv-title-' + id;
	},

	overlay: function(dialog) {
		this.$el = $.ez.fdiv.overlay.create(dialog);
	}
});

$.extend($.ez.fdiv.overlay, {
	instances: [],
	// reuse old instances due to IE memory leak with alpha transparency (see #5185)
	oldInstances: [],
	maxZ: 0,
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				// handle $(el).dialog().dialog('close') (see #4065)
				if ($.ez.fdiv.overlay.instances.length) {
					$(document).bind($.ez.fdiv.overlay.events, function(event) {
						// stop events if the z-index of the target is < the z-index of the overlay
						// we cannot return true when we don't want to cancel the event (#3523)
						if ($(event.target).zIndex() < $.ez.fdiv.overlay.maxZ) {
							return false;
						}
					});
				}
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				if (dialog.options.closeOnEscape && event.keyCode &&
					event.keyCode === $.ui.keyCode.ESCAPE) {
					
					dialog.close(event);
					event.preventDefault();
				}
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ez.fdiv.overlay.resize);
		}

		var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay'))
			.appendTo(document.body)
			.css({
				width: this.width(),
				height: this.height(),
				position:'absolute',
				top:0,
				left:0,
				background:'#000',
				opacity: .3
			});

		if ($.fn.bgiframe) {
			$el.bgiframe();
		}
		
		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		var indexOf = $.inArray($el, this.instances);
		if (indexOf != -1){
			this.oldInstances.push(this.instances.splice(indexOf, 1)[0]);
		}

		if (this.instances.length === 0) {
			$([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
		
		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		var maxZ = 0;
		$.each(this.instances, function() {
			maxZ = Math.max(maxZ, this.css('z-index'));
		});
		this.maxZ = maxZ;
	},

	height: function() {
		var scrollHeight,
			offsetHeight;
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		var scrollWidth,
			offsetWidth;
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ez.fdiv.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ez.fdiv.overlay.width(),
			height: $.ez.fdiv.overlay.height()
		});
	}
});

$.extend($.ez.fdiv.overlay.prototype, {
	destroy: function() {
		$.ez.fdiv.overlay.destroy(this.$el);
	}
});

}(jQuery));

