/**
 * @author xing
 */
(function($){
	$.fn.simpleDialog=function(o){
		var options={
            title:'',
			iframe:'',
			iframeUrl:'',
			ajax:'',
			ajaxUrl:'',
			buttons:null,
			modal:'',
			id:'',
			cssClass:'',
			alert:'',
			alertHtml:'',
			confirm:'',
			confirmHtml:'',
			onSure:'',
			onCancel:'',
			onClose:'',
			dialogTemplate:'<div class="xq_dag"><div class="min"></div><div class="max"></div><div class="close"></div><div class="title"></div>'+
   	 						'<table><tr class="handle"><td class="tl"></td><td class="tc"></td><td class="tr"></td></tr><tr><td class="cl">'+
	 						'</td><td class="xq_wapper"><div class="xqContent"></div></td><td class="cr"></td></tr>'+
							'<tr><td class="bl"></td><td class="bc"></td><td class="br"></td></tr></table></div>'
		};
		o=$.extend(options,o);
		return $.dialog.setDialog(this,o);
	};
	$.dialog={
		setDialog:function(data,o){
			var s=this;
			if(o.iframe===true){
				var  iframe = '<iframe src=' +
                '"' +
                o.iframeUrl +
                '"' +
                ' style="border:0" id="xqframe" frameborder=0 onload="reinitIframe()"></iframe>';
				var temp=$(o.dialogTemplate).clone().addClass('iframe');
				//temp.find('div.title').text(o.title);
				temp.attr('id',o.id);
				var content=temp.find('div.xqContent');
				content.append(iframe);
				$('body').append(temp);
				$('body').find('div.close').click(function(){
					$(this).parent().remove();
			});
			$('.xq_dag').draggable({
				handle:'tr.handle'
			});
				return;
			}else if(o.ajax===true){
				if(s.checkDag('.ajax')){
					return;
				}
				var temp=$(o.dialogTemplate).clone().addClass('ajax');
				//temp.find('div.title').text(o.title);
				temp.attr('id',o.id);
				//var divAjaxLoading=$('div').appendTo()
				var content=temp.find('div.xqContent');
				var divAjaxLoading=$('<div/>').html('<span>我正在努力的加载中,请等待</span>').addClass('ajaxloading').appendTo(content);
				$('div.ajaxloading').ajaxStart(function(){
					$(this).show();
				});
				$('div.ajaxloading').ajaxStop(function(){
					$(this).hide();
				});
				content.load(o.ajaxUrl,function(){
					if (o.buttons != null) {
						content.parent().append(s.setBtns(o.buttons));
					}
					s.setPosition('div.xq_dag');
				});
			}else if(o.alert===true){
				if(s.checkDag('.xqAlert')){
					return;
				}
				o.buttons={
					'确定':function(){
						if($.isFunction(o.onSure)){
							o.onSure();
						}else{
							s.close('remove','.xqAlert');
						}
					}
				};
				var temp=$(o.dialogTemplate).clone().addClass('xqAlert').hide();
				temp.find('div.min').remove();
				temp.find('div.max').remove();
				var content=temp.find('div.xqContent');
				content.append('<div id="xq_alert">'+o.alertHtml+'</div>');
				content.parent().append(s.setBtns(o.buttons));
			}else if(o.confirm===true){
				if(s.checkDag('.xqConfirm')){
					return;
				}
				o.buttons={
					'确定':function(){
						if($.isFunction(o.onSure)){
							o.onSure();
						}else{
							s.close('remove','.xqConfirm');
						}
					},
					'取消':function(){
						if($.isFunction(o.onCancel)){
							o.onCancel();
						}else{
							s.close('remove','.xqConfirm');
						}
					}
				};
				var temp=$(o.dialogTemplate).clone().addClass('xqConfirm').hide();
				temp.find('div.min').remove();
				temp.find('div.max').remove();
				var content=temp.find('div.xqContent');
				content.append('<div id="xq_confirm">'+o.confirmHtml+'</div>');
				content.parent().append(s.setBtns(o.buttons));
			}else{
				var temp=$(o.dialogTemplate).clone().addClass('normal').hide();
				var content=temp.find('div.xqContent');
				content.append(data);
				content.parent().append(s.setBtns(o.buttons));
			}
			$('body').append(temp);
			s.setPosition(temp);
			temp.fadeIn();
			s.setSize(o);
				$('.xq_dag').draggable({
				handle:'tr.handle'
			});
		},
		/**
		 * <p>设置按钮</p>
		 * @param {Object} buttons {text:event}
		 */
		setBtns:function(buttons){
			var buttonBar=$('<div/>').addClass('buttonBar');
			hasButtons=false;
			if (typeof buttons === 'object' && buttons !== null) {
			$.each(buttons, function() {
				return !(hasButtons = true);
			});
			}
			if(hasButtons){
				$.each(buttons,function(name,event){
					event=$.isFunction(event)?event:function(){alert('error!')};
					var button=$('<input>').attr({
						'type':'button',
						'value':name
					}).unbind('click').bind('click',event).appendTo(buttonBar);
				});
			}
			return buttonBar;
		},
		setPosition:function(el){
			var ew=$(el).width();
			var eh=$(el).height()+80;
			var dw = document.documentElement.clientWidth;
            var dh = document.documentElement.clientHeight;
            var t = (dh - eh) / 2;
            var l = (dw - ew) / 2;
            if (t < 0) {
                t = 10;
            }
            if (l < 0) {
                l = 10;
            }
           $(el).css({
		   	top:t,
			left:l
		   });
		},
		checkDag:function(selector){
			if($('body').find(selector).is('div')){
				return true;
			}else{
				return false;
			}
		},
		close:function(type,el){
			this.removeAll();
			if (type == 'remove') {
				$(el).remove();
			}else{
				$(el).hide();
			}
		},
		setSize:function(o){
			var s=this;
			s.overlay();
			$('body').find('div.close').click(function(){
				if($.isFunction(o.onClose)){
					o.onClose();
				}
				var el=$(this).parent();
				if(el.hasClass('normal')){
					el.hide();
					s.removeAll();
				}else{
					$('#btnbar').find('div').each(function(){
					if($(this).data('id')==el.attr('id')){
						$(this).remove();
					}
					});
					if($('#btnbar').find('div').length<1){
						$('#btnbar').remove();
					}
					el.remove();
					s.removeAll();
				}
			});
			$('body').find('div.min').click(function(){
				var that=$(this);
				that.parent().hide();
				if(s.checkTools(that.parent())){
					return;
				}
				var p=s.genToolsandClose(that);
				if($('#btnbar').is('div')){
					$('#btnbar').append(p);
				}else{
					var btnbar=s.getBtnBar(o);
					btnbar.append(p);
				}
			});
			$('body').find('div.max').click(function(){
				var wh=s.getPagesize();
				var el=$(this).parent();
				if(el.hasClass('isLarge')){
					el.removeClass('isLarge');
					el.find('td.xq_wapper').width('auto').height('auto');
					s.setPosition(el);
				}else{
					el.css({
					top:0,
					left:0
					});
				el.addClass('isLarge');
				el.find('td.xq_wapper').width(wh.w-10).height(wh.h-30);
				}

			});
		},
		getBtnBar:function(o){
			var btnbar=$('<div/>',{
				id:'btnbar'
			}).css({
				position:'fixed',
				left:150,
				width:'100%',
				bottom:0,
				height:'30px',
				border:'1px solid #ccc',
				background:'#ebebeb'
			}).appendTo($('body'));
			return btnbar;
		},
		genToolsandClose:function(el){
			var id=el.parent().attr('id');
			var title=el.parent().find('div.title').text();
			var ps=$('<div/>');
				ps.css({
					'float':'left',
					'width':100,
					'height':'100%',
					'margin':'2px',
					'border':'1px dashed #c6c6c6',
					'background':'#fff',
					'text-align':'center'
				}).html(title).click(function(){
					el.parent().show();
			}).data('id',id);
			return ps;
		},
		//判断是否存在已经有的缩小的div
		checkTools:function(el){
			var j=1;
			$('#btnbar').find('div').each(function(){
				if($(this).data('id')==el.attr('id')){
					j=0;
				}
			});
			if(j==0){
				return true;
			}else{
				return false;
			}
		},
		 overlay: function(){
           var pageSize = this.getPagesize();
           // var lay = $('<div/>').css({
            //    position: 'absolute',
            //    width: '100%',
            //    height: '100%',
            //    opacity: 0.1,
             //   background: '#fff',
             //   filter: 'alpha(opacity=10)',
            //    zIndex: 9000
           // }).attr('id', 'overlay');
          //  lay.appendTo($(document.body));
			if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("overlay") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='HideSelect'></iframe><div id='overlay'></div>");
				$('#HideSelect,#overlay').height(pageSize.h);
			}
			}else{//all others
			if(document.getElementById("overlay") === null){
				$("body").append("<div id='overlay'></div>");
			}

		}
            //$('body').prepend(lay);
        },
		removeAll:function(){
			$('#overlay,#HideSelect').remove();
			if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
				$("body","html").css({height: "auto", width: "auto"});
				$("html").css("overflow","");
			}
		},
        getPagesize: function(){
            var w = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth);
            var h = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight);
            return {
                w: w,
                h: h
            };
        }
	}
})(jQuery)
function reinitIframe(){
				var iframe = document.getElementById("xqframe");
				$(iframe).height(100).width(300);
				try{
					var bHeight = iframe.contentWindow.document.body.scrollHeight;
					var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
					var BW = iframe.contentWindow.document.body.scrollWidth;
					var DW = iframe.contentWindow.document.documentElement.scrollWidth;
					var height = Math.max(bHeight, dHeight);
					var width=Math.max(BW,DW);
					$(iframe).height(height).width(width).css('overflow','hidden');
					$.dialog.setPosition('div.iframe');
				}catch (ex){}
}
window.setInterval("reinitIframe()", 200);

