var $jBox = function(c)
{
	return new jBox(c);
}

function closeJBox(id) {
	$jBox(id).close();
}

function jBox(c)
{
	var j = {}, ref = false;

	if (typeof c == "string") {
		c = {id: c};
	} else if (c == null || typeof c != "object") {
		c = {id:"jbox-aout-1"};
	} else if (c.nodeType) {
		j = $(c); ref = true;
	} else if (c instanceof jQuery) {
		j = c; ref = true;
	} else if (!c.id) {
		c.id = (!c.ifsrc) ? "jbox-aout-1" : "jbox-aout-2";
	}

	if (ref == false) {
		j = $("#"+c.id);
		if (!c.top && !c.left)
			c.point = "auto";
	}

	if (j.length) {
		this.makeBox(j);
	} else {
		this.createBox(c)
	}
	if (ref == false)
	{
		this.resize(c).setTitle(c.title).show();
		if (c.ifsrc) this.loadFrame(c.ifsrc);
		else if (c.url)	this.load(c.url, c.init);
		else if (c.msg)	this.setText(c.msg);
	}
}

jBox.fn = jBox.prototype;

jBox.fn.makeBox = function(j)
{
	if ( !(j instanceof jQuery) || j.length == 0 ) return this;

	if ( j.hasClass("jbox-frame") )
		this.box = j;
	else
		this.box = j.parents(".jbox-frame");
	if (this.box.length != 0)
	{
		this.ttl = this.box.children(".jbox-title");
		this.cls = this.box.children(".jbox-close");
		this.ctt = this.box.children(".jbox-content");
	}
	return this;
}

jBox.fn.createBox = function(c)
{
	var iw, ih, ow, oh, tw, cw;
	iw = 200;
	ih = 200;
	ow = iw + 14;
	oh = ih + 44;
	cw = 70;
	tw = iw - cw - 5;
	var boxCss = {
			display: "none",
			position: "absolute",
			border: "2px outset #AAA",
			width: ow,
			height: oh,
			backgroundImage: "url(./js/bkimg.gif)",
			backgroundRepeat: "repeat-x",
			backgroundColor: "#D9E6F9",
			left: 0,
			top: 0,	
			margin: "0px",
			padding: "5px 5px 10px 5px",
			textAlign: "center"
			};
	var topCss = {
			cssFloat: "left",
//			border: "1px solid #AAA",
			width: tw,
			height: "20px",
			padding: "3px 0px 3px 15px",
			textAlign: "left",
			color: "#336",
			fontWeight: "bold",
			fontSize: "18px"
			};

	var closeCss = {
			cssFloat: "right",
//			border: "1px solid #AAA",
			width: cw,
			height: "25px",
			padding: "2px",
			fontSize: "15px",
			textAlign: "right"
			};
	var contentCss = {
			clear: "both",
			border: "3px double #aaa",
			backgroundColor: "#FFF",
			width: iw,
			height: ih,
			overflow: "auto",
			textAlign: "left"
			};

	if (c.modal)
	{
		var doc = $(document);
		var modalCss = {
				position: "absolute",
				width: doc.width(),
				height: doc.height(),
				left: 0,
				top: 0,	
				padding: "0px",
				margin: "0px",
				opacity: 0.7,
				backgroundColor: "#666"
				};
		$("<div></div>").css(modalCss).appendTo("body").addClass("jbox-modal");
	}
	if (c.msg)
		contentCss.textAlign = "center";
	if (c.hideclose)
		closeCss.visibility = "hidden"; 

	var temp = "<div><a href=\"#\" onclick=\"return $jBox(this).close();\"> " + 
						"閉じる <img border=\"0\" src=\"./js/close.gif\" width=\"16\" height=\"16\"></a></div>";
	this.box = $("<div></div>").css(boxCss).appendTo("body").addClass("jbox-frame");
	this.ttl = $("<div></div>").css(topCss).appendTo(this.box).addClass("jbox-title");
	this.cls = $(temp).css(closeCss).appendTo(this.box).addClass("jbox-close")
					.children("<a>").css({color: "#F60", textDecoration: "none"});
	if (!c.ifsrc) {
		temp = "<div></div>";
	} else {
		c.url = "";
		temp = "<iframe frameborder=\"0\" name=\"" + c.id + "_ifrm" + "\" width=\"200\" height=\"200\">データ読み込み中・・・<br /><br />画面が表示されない場合は<a href=\"" + c.ifsrc +"\">こちら</a>をクリックして下さい。</iframe>";
	}
	this.ctt = $(temp).css(contentCss).appendTo(this.box).addClass("jbox-content");

	if (c.id)	this.box.attr("id", c.id);
//	if (!c.modal)
		this.ttl.bind("mousedown", this.box.get(0), drag);
	return this;
}

jBox.fn.resize = function(c)
{
	var w, h, t1, t2;
	var css1={}, css2={}, css3={};
	if (!this.box || this.box.length == 0 || !c) return this;
	if (c.width && c.width > 100) {
		css3.width = c.width;
		css1.width = css3.width + 14;
		css2.width = css3.width - 75;
	}
	if (c.height && c.height > 60) {
		css3.height = c.height;
		css1.height = css3.height + 44;
	}

	var r = this.getWindowSize();
	w = css1.width || this.box.width();
	h = css1.height || this.box.height();
	if (c.point && c.point == "auto") {
		css1.left = (r.w - w) / 2 + r.x;
		css1.top = (r.h - h) / 2 + r.y;
	} else if (c.point && c.point == "mouse") {
		t1 = c.left ? c.left - (w / 2) : 0;
		t2 = c.top ? c.top - 35 : 0;
		if (t1 < 0)	t1 = 0;
		else if ((t1+w+10) > r.w )	t1 = r.w - w - 10;
		if (t2 < 0)	t2 = 0;
		else if ((t2+h+10) > r.h )	t2 = r.h - h - 10;
		css1.left = t1 + r.x;
		css1.top = t2 + r.y;
	} else {
		if (c.left != null)
			css1.left = c.left;
		if (c.top != null)
			css1.top = c.top;
	}
	this.box.css(css1);
	this.ttl.css(css2);
	this.ctt.css(css3);
	return this;
}

jBox.fn.getWindowSize = function()
{
	var r = {};
	var doc = (document.documentElement && document.documentElement.clientWidth) ? document.documentElement : document.body;
	r.w = window.innerWidth || doc.clientWidth;
	r.h = window.innerHeight || doc.clientHeight;
	r.x = window.pageXOffset || doc.scrollLeft;
	r.y = window.pageYOffset || doc.scrollTop;
	return r;
}

jBox.fn.show = function()
{
	if (!this.box || this.box.length == 0) return this;
	this.box.fadeIn("fast");
	return this;
}

jBox.fn.hide = function()
{
	if (!this.box || this.box.length == 0) return this;
	this.box.fadeOut("fast");
	return this;
}

jBox.fn.close = function(retVal)
{
	if (!this.box || this.box.length == 0) return this;
	this.box.remove();
	$(".jbox-modal").remove();
	return retVal || false;
}

jBox.fn.content = function() {
	return this.ctt || {};
}

jBox.fn.title = function() {
	return this.ttl || {};
}

jBox.fn.frame = function() {
	return this.box || {};
}

jBox.fn.setTitle = function(title)
{
	if (!this.ttl || this.ttl.length == 0 || title == null) return this;
	this.ttl.html(title);
	return this;
}

jBox.fn.load = function(filename, callback)
{
	if (!this.ctt || this.ctt.length == 0 || filename == null) return this;
	this.ctt.load(filename, callback);
	return this;
}

jBox.fn.loadFrame = function(src)
{
	if (!this.ctt || this.ctt.length == 0 || src == null) return this;
	this.ctt.attr("src", src);
	return this;
}

jBox.fn.setText = function(text)
{
	if (!this.ctt || this.ctt.length == 0) return this;
	var a = "<br /><p>"+text+"</p>";
	this.ctt.html(a);
	return this;
}

function drag(v) {
	var a = v.data;
	var sx = v.clientX, sy = v.clientY;    
	var ox = a.offsetLeft, oy = a.offsetTop;
	var dx = sx - ox, dy = sy - oy;
	var d = document;

	if (d.addEventListener) {
		d.addEventListener("mousemove", moveHandler, true);
		d.addEventListener("mouseup", upHandler, true);
	} else if (d.attachEvent) {
		a.setCapture();
		a.attachEvent("onmousemove", moveHandler);
		a.attachEvent("onmouseup", upHandler);
		a.attachEvent("onlosecapture", upHandler);
    } else {
		var oldmovehandler = d.onmousemove; // used by upHandler() 
		var olduphandler = d.onmouseup;
		d.onmousemove = moveHandler;
		d.onmouseup = upHandler;
	}
	if (v.stopPropagation) v.stopPropagation();
	else v.cancelBubble = true;

	if (v.prvDefault) v.prvDefault();
	else v.returnValue = false;

	function moveHandler(e) {
		if (!e) e = window.v;
		a.style.left = (e.clientX - dx) + "px";
		a.style.top = (e.clientY - dy) + "px";
		if (e.stopPropagation) e.stopPropagation();
		else e.cancelBubble = true;
	}
	function upHandler(e) {
		if (!e) e = window.v;

		if (d.removeEventListener) {
			d.removeEventListener("mouseup", upHandler, true);
			d.removeEventListener("mousemove", moveHandler, true);
		} else if (d.detachEvent) {
			a.detachEvent("onlosecapture", upHandler);
			a.detachEvent("onmouseup", upHandler);
			a.detachEvent("onmousemove", moveHandler);
			a.releaseCapture();
		} else {
			d.onmouseup = olduphandler;
			d.onmousemove = oldmovehandler;
		}

		if (e.stopPropagation) e.stopPropagation();
		else e.cancelBubble = true;
	}
}


jQuery.fn.corner = function(o) {
    function hex2(s) {
        var s = parseInt(s).toString(16);
        return ( s.length < 2 ) ? '0'+s : s;
    };
    function gpc(node) {
        for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode  ) {
            var v = jQuery.css(node,'backgroundColor');
            if ( v.indexOf('rgb') >= 0 ) { 
                rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            if ( v && v != 'transparent' )
                return v;
        }
        return '#ffffff';
    };
    function getW(i) {
        switch(fx) {
        case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
        case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
        case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
        case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
        case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
        case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
        case 'curl':   return Math.round(width*(Math.atan(i)));
        case 'tear':   return Math.round(width*(Math.cos(i)));
        case 'wicked': return Math.round(width*(Math.tan(i)));
        case 'long':   return Math.round(width*(Math.sqrt(i)));
        case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
        case 'dog':    return (i&1) ? (i+1) : width;
        case 'dog2':   return (i&2) ? (i+1) : width;
        case 'dog3':   return (i&3) ? (i+1) : width;
        case 'fray':   return (i%2)*width;
        case 'notch':  return width; 
        case 'bevel':  return i+1;
        }
    };
    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt(jQuery.css(this,'paddingTop'))||0,     R: parseInt(jQuery.css(this,'paddingRight'))||0,
            B: parseInt(jQuery.css(this,'paddingBottom'))||0,  L: parseInt(jQuery.css(this,'paddingLeft'))||0
        };

        if (jQuery.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = jQuery.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
            var d = document.createElement('div');
            var ds = d.style;

            bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

            if (bot && cssHeight != 'auto') {
                if (jQuery.css(this,'position') == 'static')
                    this.style.position = 'relative';
                ds.position = 'absolute';
                ds.bottom = ds.left = ds.padding = ds.margin = '0';
                if (jQuery.browser.msie)
                    ds.setExpression('width', 'this.parentNode.offsetWidth');
                else
                    ds.width = '100%';
            }
            else {
                ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                    (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
            }

            for (var i=0; i < width; i++) {
                var w = Math.max(0,getW(i));
                var e = strip.cloneNode(false);
                e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
            }
        }
    });
};

