﻿/* *************************************************************
	EXBOX PLUGIN, 2010/10/28 16:15, Yan Gang. HITIS.CN

	MILESTONE DATE: 2010/11/10 11:30

	MILESTONE 2 DATE: 2010/11/25 18:24

	MILESTONE 3 DATE: 2011/3/1 14:08
	
	VERSION 1.0

	FEATURES: so easy :)
************************************************************* */
var exbox = function () {

	this.id = Math.random().toString().replace(/\./ig, '');

	this.config = {
		width:'auto',
		height:'auto',
		visible:false,
		autosize:false,
		autoload:true,
		url:null,
		html:null,
		onstatushandler:null,
		onhandler:null,
		title:'Message',
		titlevisible:true,
		commandvisible:true,
		bordervisible:true,
		padding:2,
		lifetime:0,
		anykey:false,
		async:true,
		buttons:null,
		defaultbutton:null,
		okbuttonvisible:true,
		cancelbuttonvisible:true
	};

	this.vars = {
		mask_id:null,
		win_id:null,
		url_data:null,
		status:'INIT',
		prefix:'exbox',
		mask_class:'exbox_mask_modal',
		win_class:'exbox_win_modal',
		_overflow:null
	};

	this.string = {
		waiting:'<div style="padding:20px 40px;text-align:center;min-width:180px;"><img src="/static/plugins/exbox/indicator_blue_small.gif" alt="" /> 请稍候...</div>',
		failure:'<div style="padding:20px 40px;text-align:center;min-width:180px;"><img src="/static/plugins/exbox/mb_message_title_icon.gif" alt="" /> 页面载入失败。</div>',
		submit:'确定',
		reset:'关闭'
	};

	this._lifetimer = null;

	this._css2_compatible = !($.browser.msie && parseFloat($.browser.version) <= 7);


	
	this.alert = function(){
		var sz = arguments[0]||'';
		var f = arguments[1]||function(){};
		var w = 480;
		return (new exbox()).create(
			{ 
				padding: 20, 
				width: w, 
				async: false,
				onstatushandler: function(msg) { if (msg == 'CLOSE' && f) f(); },
				okbuttonvisible: false,
				title: '<img src="/static/plugins/exbox/mb_message_title_icon.gif" alt="" style="vertical-align:middle" /> 消息', 
				html: sz+""
			}
			).show();
	};

	this.notice = function(){
		var sz = arguments[0]||'';
		var f = arguments[1]||function(){};
		var w = 480;
		return (new exbox()).create(
			{ 
				padding: 20, 
				width: w, 
				async: false,
				onstatushandler: function(msg) { if (msg == 'CLOSE' && f) f(); },
				okbuttonvisible: false,
				cancelbuttonvisible: false,
				title: '<img src="/static/plugins/exbox/mb_message_title_icon.gif" alt="" style="vertical-align:middle" /> 消息', 
				html: sz+""
			}
			).show();
	};

	this.confirm = function(){
		var sz = arguments[0]||'';
		var f = arguments[1]||function(){};
		var w = 480;
		return (new exbox()).create(
			{ 
				padding: 20, 
				width: w, 
				async: false,
				onhandler: function() { if (f) f(); }, 
				title: '<img src="/static/plugins/exbox/mb_message_title_icon.gif" alt="" style="vertical-align:middle" /> 确认', 
				html: sz+""
			}
			).show();
	};

};




exbox.prototype._read_config = function(args){
	
	try
	{
		if(args.length==0) return;	
	}
	catch (x)
	{
		return;
	}

	if(typeof args[0]=='object'){
		with(args[0]) {
			if(typeof width=='number') this.config.width=width;
			if(typeof height=='number') this.config.height=height;
			if(typeof padding=='number') this.config.padding=padding;

			if(typeof title=='string') this.config.title=title;
			if(typeof url=='string') this.config.url=url;
			if(typeof html=='string') this.config.html=html;

			if(typeof visible=='boolean') this.config.visible=visible;
			if(typeof autosize=='boolean') this.config.autosize=autosize;
			if(typeof autoload=='boolean') this.config.autoload=autoload;
			if(typeof titlevisible=='boolean') this.config.titlevisible=titlevisible;
			if(typeof commandvisible=='boolean') this.config.commandvisible=commandvisible;
			if(typeof bordervisible=='boolean') this.config.bordervisible=bordervisible;
			if(typeof anykey=='boolean') this.config.anykey=anykey;
			if(typeof async=='boolean') this.config.async=async;

			if(typeof lifetime=='number') this.config.lifetime=lifetime;

			if(typeof onstatushandler=='function') this.config.onstatushandler=onstatushandler;
			if(typeof onhandler=='function') this.config.onhandler=onhandler;

			if(typeof buttons=='object') this.config.buttons=buttons;
			if(typeof defaultbutton=='string') this.config.defaultbutton=defaultbutton;

			if(typeof okbuttonvisible=='boolean') this.config.okbuttonvisible=okbuttonvisible;
			if(typeof cancelbuttonvisible=='boolean') this.config.cancelbuttonvisible=cancelbuttonvisible;

		}
	}
}
exbox.prototype.create = function() {

	if(!$) {
		return 'need jQuery.';
	}
    var args = arguments;

	if(args.length>0)
		this._read_config(args);

    this.vars.mask_id = this.config.prefix+'_mask_' + Math.random().toString().replace(/\./ig, '');
    $('#' + this.vars.mask_id).remove();
    this.vars.win_id = this.config.prefix+'_win_' + Math.random().toString().replace(/\./ig, '');
    $('#' + this.vars.win_id).remove();

    this._onstatushandle("READY");

	if(this.config.autoload){
		if(this.config.url){
			this.load(this.config.url);
		}
	}


	return this;

};

exbox.prototype.show = function() {
	
	
	if(this.vars.status=="INIT") return;

	var _this=this;

	this._create_mask();

	this._create_window();

	this.config.visible = true;
		
	if(_this.vars.status=="LOAD_COMPLETE"||_this.vars.status=="CLOSE"||_this.vars.status=="READY") {

		if(_this.config.lifetime>0)
			_this._lifetimer = window.setTimeout(function(){ _this.close() },_this.config.lifetime);

		this._onstatushandle("SHOW");
	}

	return this;
};

//此指令执行将不可逆转
exbox.prototype.close = function(){
	var _this=this;


	// 判断关闭延时指示
    var args = arguments;
	if(args.length>0){
		timer=args[0];
		if(typeof timer=='number'&&timer>0){
			window.setTimeout(function(){_this.close()},timer);
			return;
		}
	}
	// ---


	this.config.visible = false;



	$("#" + this.vars.win_id).hide();
	$("#" + this.vars.mask_id).fadeOut('fast', function() {
		_this._clear_mask();
		_this._clear_window();
		_this._onstatushandle("CLOSE");
	});
};



exbox.prototype.load = function() {
	var _this=this;
	

	var args = arguments;
	if(args.length>0)
		if(typeof args[0]=='string')
			if(args[0])
				this.config.url = args[0];
	
    _this._onstatushandle("LOADING");
    this.vars.url_data = this.string.waiting;
    $.ajax({
        type: "GET",
        url: this.config.url,
        dataType: "html",
		cache: false,
		async: this.config.async,
        success: function(msg) {
            _this.vars.url_data = msg;
            _this._onstatushandle("LOAD_COMPLETE");
            if (_this.config.visible) {
				_this.show();
            }
        },
        error: function(x) {
            _this._onstatushandle("LOAD_FAILURE");
            _this.vars.url_data = _this.string.failure;
            if (_this.config.visible) _this._create_window();
        }
    });

}


exbox.prototype.__bind_event = function(event) {
	event.data.exbox._align();
}

exbox.prototype._align = function() {
    
	var _this = this;
    var mask = $("#" + _this.vars.mask_id);
    var win = $("#" + _this.vars.win_id);

    if (mask.length == 0||win.length ==0) return;

	
    var scrw = $(window).width();
    var scrh = $(window).height();

    var winw = win.outerWidth();
    var winh = win.outerHeight();

	

    var sw = document.documentElement.clientWidth > document.body.clientWidth
    ? document.documentElement.clientWidth : document.body.clientWidth + document.body.scrollLeft;

    var sh = document.documentElement.clientHeight > document.body.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;

	var dcw=document.documentElement.clientWidth;
	var dch=document.documentElement.clientHeight;
	var dsw=document.documentElement.scrollWidth;
	var dsh=document.documentElement.scrollHeight;

	//alert(document.body.clientHeight+":"+document.documentElement.clientHeight+":"+dsh);


	sw = Math.max(dsw,dcw);
	sh = Math.max(dsh,dch);


    mask.css("width", sw + "px");
    mask.css("height", sh + "px");

    try {
        var doct = $(document).scrollTop();

        var t = (scrh - winh) / 2 + doct;


        win.css("top", Math.max(0,t) + "px");

        var docl = $(document).scrollLeft();

        var l = (scrw - winw) / 2 + docl;

        win.css("left",Math.max(0,l) + "px");

    } catch (x) { }

}


exbox.prototype._clear_mask = function() {
    if (!this.vars.mask_id) return;
    $("#" + this.vars.mask_id).remove();

    $(window).unbind("resize",this.__bind_event);

	//还原overflow
	//document.body.style.overflow=this.vars._overflow;
	$("body").css("overflow",	this.vars._overflow);
}


exbox.prototype._create_mask = function() {
	var _this=this;

	//保存并改变overflow
	//this.vars._overflow=document.body.style.overflow;
	//document.body.style.overflow="hidden";
	this.vars._overflow=$("body").css("overflow");
	$("body").css("overflow",	"hidden");


    var mask = document.createElement("div");
    mask.id = this.vars.mask_id;
    mask.className = this.vars.mask_class;

    document.body.appendChild(mask);
    _this._align();

    $(window).bind("resize",{ exbox:_this },_this.__bind_event);
}

exbox.prototype._clear_window = function() {
    if (!this.vars.win_id) return;
    $("#" + this.vars.win_id).remove();
}

exbox.prototype._create_window = function() {

	var _this=this;

    $("#" + this.vars.win_id).remove();

    var w = document.createElement("div");
    w.style.visibility = "hidden";
    w.className = this.vars.win_class;
    w.id = this.vars.win_id;



    var d = document.createElement("div");
    d.style.cssText = 'overflow:auto;';


	var sz='',sb='',st='',sc='';

	st+='	<div class="exbox_titlebar">';
	//st+='		<a class="exbox_button_close"></a>';
	st+='		<span>{$title}</span>';
	st+='		<div class="clear"></div>';
	st+='	</div>';	
	
	sb+='	<div class="exbox_content_container">';
	sb+='		<div class="exbox_content_container_padding">';
	sb+='			{$content}';
	sb+='		</div>';
	sb+='		<div class="clear"></div>';
	sb+='	</div>';
	
	sc+='	<div class="exbox_commandbar">';
	sc+='		<div class="exbox_command_container">';
	sc+='		</div>';
	sc+='		<div class="clear"></div>';
	sc+='	</div>';


	if(this.config.titlevisible) { sz+=st; }
	sz+=sb;
	if(this.config.commandvisible) { sz+=sc; }

	sz=sz.replace(/\{\$title\}/ig,this.config.title)
		 .replace(/\{\$content\}/ig,
			(this.vars.url_data||this.config.html||'').replace(/\\n/ig,'<br />'));


	var exbox_container = document.createElement("div");
	exbox_container.className = 'exbox_container';
	exbox_container.innerHTML = sz;

	d.appendChild(exbox_container);	

	//初始化各部分组件

	var ec = $(d).find('.exbox_container');
	var etb = $(d).find('.exbox_titlebar');
	var ecc = $(d).find('.exbox_content_container');
	var eccp = $(d).find('.exbox_content_container_padding');
	var ecmd = $(d).find('.exbox_commandbar');
	var button_zone = $(d).find('.exbox_command_container');


	//增加按钮	
	if(this.config.commandvisible){

		if(this.config.buttons) {	
			for(var i in this.config.buttons){
				if(typeof i=='string') {
					var btn=document.createElement("input");
					btn.type='button';
					btn.value=i;
					btn.onclick=_this.config.buttons[i];
					if(_this.config.defaultbutton==i)
						btn.className='default';
					button_zone[0].appendChild(btn);
				}
			}
		}
		if(this.config.okbuttonvisible){
			var btn_submit=document.createElement("input");
			btn_submit.type='submit';
			btn_submit.value=this.string.submit;
			button_zone[0].appendChild(btn_submit);
		}
		if(this.config.cancelbuttonvisible){
			var btn_reset=document.createElement("input");
			btn_reset.type='reset';
			btn_reset.value=this.string.reset;
			button_zone[0].appendChild(btn_reset);

			etb.prepend('<a class="exbox_button_close"></a>');

		}
	}


	if(!this.config.bordervisible) {
		ec.css('border','none');
		eccp.css('padding','0');
	}

	eccp.css('padding',this.config.padding);
	eccp.css('width',this.config.width);
	eccp.css('height',this.config.height);

	//$(d).css('width',this.config.width+this.config.padding*2+(this.config.bordervisible?2:0));
    //绑定命令事件
    $(etb).find('input[type=button]').each(function() {
        var s = $(this).html();
        if (s.toUpperCase() == "X") {
            $(this).click(function() { _this.close(); });
        }
    });
    $(etb).find('.exbox_button_close').each(function() {
        $(this).click(function() { _this.close(); });
    });

    $(ecmd).find('input[type=reset]').each(function() {
        $(this).click(function() {
            _this.close();
            return false;
        });
    });

    $(ecmd).find('input[type=submit]').each(function() {

        $(this).click(function() {
            _this._onhandle();

        });
    });

    w.appendChild(d);


    document.body.appendChild(w);
	

	$(d).css('width',eccp.outerWidth());

    _this._align();


	$("#" + _this.vars.win_id).css("visibility", "visible");
	$("#" + _this.vars.win_id).focus();

}


exbox.prototype._onstatushandle = function(obj) {	
	this.vars.status = obj;
    if (this.config.onstatushandler) {
        this.config.onstatushandler(obj);
    }
};
exbox.prototype._onhandle = function() {
    if (this.config.onhandler) {
        var handler_result = this.config.onhandler();
        if (handler_result || handler_result == null)
            this.close();
    } else {
        this.close();
    }
};











jQuery.extend({
    alert:(new exbox()).alert,
    notice:(new exbox()).notice,
    confirm:(new exbox()).confirm
});


