// var g_images_path = "images/";
// var g_cgi_path = "gbgate.cgi";

var GB_MESSAGES = new Object();
GB_MESSAGES['error'] = 'エラーが発生しました。';
GB_MESSAGES['InformationUpdateError'] = '情報の更新でエラーが発生しました。';
GB_MESSAGES['NoCrdID'] = '指定されたIDの座標系(crd)が見つかりませんでした。';
GB_MESSAGES['ThereisNoObject'] = '指定されたオブジェクトがありませんでした。';

var RDF_NS = ["rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"];
var GB_NS = ["gb", "http://www.globalbase.org/spec/http-rss/0.1/"];

function gbGetHttpStatusCode(req){
	var statusLine = req.getResponseHeader("X-GB-Server-Status-Line");
	return parseInt(statusLine.substr(statusLine.indexOf(" ")));
}

function gbPoint(x,y)
{
	if(x == undefined){
		this.x = 0;
		this.y = 0;
	}
	else{
		this.x = x;
		this.y = y;
	}
}

gbPoint.prototype.fromXML = function(x)
{
	this.x = x.getAttribute("x");
	this.y = x.getAttribute("y");
}

gbPoint.prototype.toQuery = function()
{
	return this.x+"_"+this.y;
}

function gbRect(l,t,r,b)
{
    this.left = l;
    this.top = t;
    this.right = r;
    this.bottom = b;
}

gbRect.prototype.hitTest = function(x,y){
    if(this.left <= x && x <= this.right && 
        this.top <= y && y <= this.bottom){
        return true;
	}
	return false;
}



function gbPosition(type,x,y,rot,reso)
{
	this.type = type;
	this.center = new gbPoint(x,y);
	if(rot == undefined){
		this.rotate = 0;
	}
	else{
		this.rotate = rot;
	}
	if(reso == undefined){
		this.reso = 100;
	}
	else{
		if(gbPosition.maxReso!=null){
			if(reso>gbPosition.maxReso){
				reso = gbPosition.maxReso;
			}
		}
		this.reso = reso;
	}
}

gbPosition.maxReso=null;
gbPosition.prototype.toQuery = function()
{
	// a-[中心座標x]-[中心座標y]-[回転角(度)]-[レゾリューション]
	return this.type+"_"+this.center.x+"_"+this.center.y+"_"+this.rotate+"_"+this.reso;
}



function gbTarget()
{
	this.coord = 1;
	this.position = null;
}

gbTarget.prototype.initByXML = function(x){
	var type = x.getAttribute("type");
	if(type == null){
		type = "a";
	}
	var maxReso = x.getAttribute("maxReso");
	if(maxReso){
		gbPosition.maxReso = maxReso;
	}
	
	this.position = new gbPosition(
		type,
		parseFloat(x.getAttribute("cx")), 
		parseFloat(x.getAttribute("cy")), 
		parseFloat(x.getAttribute("rotate")), 
		parseFloat(x.getAttribute("reso"))
		);
	
	this.coord = x.getAttribute("coord");
	
}


gbTarget.prototype.updateByParamStr = function(paramStr)
{
	var params = paramStr.split("_");
	this.coord = decodeURIComponent(params[0]);
	this.position = new gbPosition(
			params[1],
			parseFloat(params[2]),
			parseFloat(params[3]),
			parseFloat(params[4]),
			parseFloat(params[5])
		);
}


gbTarget.prototype.toQuery = function()
{
	return "" + encodeURIComponent(this.coord) + "_" + this.position.toQuery();
}

function gbObj()
{
    
}

gbObj.prototype.getApp = function()
{
	if(this.app){
		return this.app;
	}
	return null;
}

function gbCoord(app)
{
	this.visible = true;
	this.owner = null;
	this.id = "";
	this.name = "";
	this.locked = false;
	this.isBase = false;
	this.app = app;
}

gbCoord.prototype = new gbObj();

gbCoord.prototype.initByXML = function(coordXML)
{
	this.visible = coordXML.getAttribute("visible") != "false";
	this.id = coordXML.getAttribute("id");
	this.name = coordXML.getAttribute("name");
	this.locked = (coordXML.getAttribute("locked") == "true");
	this.isBase =  (coordXML.getAttribute("base") == "true");
	this.xml = coordXML;
}

gbCoord.prototype.toQuery = function()
{
	return encodeURIComponent(this.id + "(" + (this.locked?"L":"") + (this.visible?"1":"0") + ")");
}

gbCoord.prototype.getHTML = function()
{
	return "<tr><td><div class='coord_style'>"+this.name+"</div></td></tr>";
}

function gbLayerItem()
{
	this.dispDesc = false;
}

gbLayerItem.prototype = new gbObj();

gbLayerItem.prototype.getVisibleBtnId = function()
{
	return "v"+this.getApp().id+"_"+this.id;
}

gbLayerItem.setVisible = function(obj, v){
	obj.visible = v;
	var btn = getObjectById(obj.getVisibleBtnId());
	if(btn && btn.src){
		btn.src = obj.getVisibleImagePath(v);
	}
	return true;
}

gbLayerItem.prototype.setVisible = function(v){
	return gbLayerItem.setVisible(this,v);
}

gbLayerItem.prototype.getVisibleImagePath = function(v){
	var app = this.getApp();
	if(v){
		return  app.getImagesPath() + "eye_open.gif"
	}
	else{
		return  app.getImagesPath() + "eye_close.gif"
	}
}

function gbLayer(app)
{
	this.coords = null;
	this.visible = true;
	this.name = "";
	this.id = "";
	this.app = app;
}

gbLayer.prototype = new gbLayerItem();

gbLayer.prototype.initByXML = function(layerXML)
{
    this.visible = (layerXML.getAttribute("visible") != "false");
	this.name = layerXML.getAttribute("name");
	this.id = layerXML.getAttribute("id");
	
	var children = layerXML.childNodes;
	var coordCount = 0;
	for(var i=0; i<children.length; ++i){
		if(children[i].nodeType == 1){
			if(children[i].nodeName=="coord"){
				++coordCount;
			}
		}
	}

	var idx = 0;
	this.coords = new Array(coordCount);
	for(var i=0; i<children.length; ++i){
		if(children[i].nodeType == 1){
			if(children[i].nodeName=="coord"){
				this.coords[idx] = new gbCoord();
				this.coords[idx].initByXML(children[i]);
				++idx;
			}
			else if(children[i].nodeName=="desc"){
				this.desc = getChildrenText(children[i]);
			}
		}
	}
	this.xml = layerXML;
}

gbLayer.prototype.toQuery = function()
{
	return encodeURIComponent(this.id) + (this.visible?"[1]":"[0]");
}


gbLayer.prototype.getHTML = function()
{
	return gbGetLayerRowHTML(this);
}

gbLayer.prototype.getCoords = function()
{
	return this.coords;
}

gbLayer.prototype.updateDepth = function(depth){
	this.depth = depth;
}

gbLayer.prototype.getItemById = function(id){
	if(this.id  == id){
		return this;
	}
	return null;
}

gbLayer.prototype.updateByParams = function(params){
	var i=0;
	var v=false;
	for(; i<params.length; ++i){
		if(params[i][0] == this.id){
			v = (params[i][1]=="1");
			this.setVisible(v);
			break;
		}
	}
	return v;
}


function gbLayerGroup(app)
{
	this.init(app);
}

gbLayerGroup.prototype = new gbLayerItem();



gbLayerGroup.prototype.init = function(app)
{
	this.max_layer = 20;
	this.htmlId = "layerGroup";
	this.id = 0;
	this.layers = null;
	this.name = null;
	this.visible = true;
	this.app = app;
	this.expand = true;
}


gbLayerGroup.prototype.initByXML = function(layerGroupXML)
{
	var htmlId = layerGroupXML.getAttribute("htmlId");
	if(htmlId != null){
		this.htmlId = htmlId;
	}
	
	var name = layerGroupXML.getAttribute("name");
	if(name != null){
		this.name = name;
	}
	
	var id = layerGroupXML.getAttribute("id");
	if(id != null){
		this.id = id;
	}
	
	this.visible = layerGroupXML.getAttribute("visible")!="false";
	this.expand = layerGroupXML.getAttribute("expand")!="false";
	
	this.xml = layerGroupXML;
	
	var children = layerGroupXML.childNodes;
	
	this.layers = new Array();
	var leyIndex=0;
	for(var i=0; i<children.length; ++i){
		if(children[i].nodeType == 1){
			var node = children[i];
			var newItem=null;
			switch(node.nodeName){
				case "layer":
					newItem = new gbLayer(this.app);
					break;
				case "layerGroup":
					newItem = new gbLayerGroup(this.app);
					break;
				case "desc":
					this.desc = getChildrenText(node);
					break;
			}
			if(newItem!=null){
				newItem.initByXML(node);
				this.layers[leyIndex++] = newItem;
			}
		}
	}
}


gbLayerGroup.prototype.toQuery = function()
{
	var ret="";
	for(var i=0; i<this.layers.length; ++i){
		ret += this.layers[i].toQuery();
	}
	return ret;
}

gbLayerGroup.prototype.getCoords = function()
{
	var ret = new Array();
	if(this.layers != null){
		for(var i=0; i<this.layers.length; ++i){
			var coords = this.layers[i].getCoords();
			if(coords && coords.length>0){
				ret = ret.concat(coords);
			}
		}
	}
	return ret;
}


gbLayerGroup.prototype.updateByParams = function(params){
	var v = false;
	for(var i=0; i<params.length; ++i){
		if(params[i][0] == this.id){
			v = params[i][1]=="1";
			this.setVisible(v);
			break;
		}
	}
	
	for(var i=0; i<this.layers.length; ++i){
		if(this.layers[i].updateByParams(params)){
			this.expand = true;
		}
	}
	return v;
}


function gbSwitchExpand(appid, id){
	var item = gbApp.instances[appid].layerCtrl.getItemById(id);
	if(item != null){
		item.expand = !item.expand;
	}
	gbApp.instances[appid].layerCtrl.update();
}


function gbSwitchVisible(appid, id){
	var app = gbApp.instances[appid];
	var item = app.layerCtrl.getItemById(id);
	if(item != null){
		item.setVisible(!item.visible);
		
		app.updateImage(false);
	}
}

function gbShowDesc(ctrl, appid, id){
	var app = gbApp.instances[appid];
	var item = app.layerCtrl.getItemById(id);
	item.dispDesc = !item.dispDesc;
	app.layerCtrl.update();
}

function gbGetLayerRowHTML(obj)
{

	var begin_cell = "<td class=\""+(obj.xml.nodeName)+"_cell_style\" >";
	
	var ret = "<tr class=\""+(obj.xml.nodeName)+"_row_style\">";
	
	var image_src;
	if(obj.expand!=undefined){
		if(obj.expand){
			image_src = obj.getApp().getImagesPath() + "expand.gif";
		}
		else{
			image_src = obj.getApp().getImagesPath() + "unexpand.gif";
		}
		ret += begin_cell+getClickableImageHTML(image_src, "gbSwitchExpand('"+obj.getApp().id+"','"+obj.id+"')")+"</td>";
	}
	else{
		ret += begin_cell + "</td>";
	}
	
	if(obj.visible){
		image_src = obj.getVisibleImagePath(true);
	}
	else{
		image_src = obj.getVisibleImagePath(false);
	}
	
	ret += begin_cell+getClickableImageHTML(image_src, "gbSwitchVisible('"+obj.getApp().id+"','"+obj.id+"')", obj.getVisibleBtnId())+"</td>";
	
	ret += begin_cell;
	if(obj.depth){
		for(var i=0; i<obj.depth; ++i){
			ret+="&nbsp;&nbsp;&nbsp;&nbsp;";
		}
	}
	if(obj.desc){
		ret+="<span style=\"cursor:pointer\" onClick=\"gbShowDesc(this,'"+obj.getApp().id+"','"+obj.id+"')\">" + obj.name + "</span>";
		if(obj.dispDesc){
			ret+="<br><span class='desc_style'>"+obj.desc+"</span>";
		}
	}
	else{
		ret+=obj.name;
	}
	ret+="</td>";
	
	
	ret+="<tr>";
	return ret;
}



gbLayerGroup.prototype.getHTML = function()
{
	var ret = gbGetLayerRowHTML(this);
	if(this.layers != null && this.expand){
		for(var i=0; i<this.layers.length; ++i){
			ret += this.layers[i].getHTML();
		}
	}
	return ret;
}

gbLayerGroup.prototype.updateDepth = function(depth){
	this.depth = depth;
	for(var i=0; i<this.layers.length; ++i){
		this.layers[i].updateDepth(depth+1);
	}
}

gbLayerGroup.prototype.setVisible = function(v){
// trace("gbLayerGroup.prototype.setVisible called");
	if(!gbLayerItem.setVisible(this, v)){
		return false;
	}
	for(var i=0; i<this.layers.length; ++i){
		if(!this.layers[i].setVisible(v)){
			return false;
		}
	}
	return true;
}

gbLayerGroup.prototype.getItemById = function(id)
{
	if(this.id == id){
		return this;
	}
	for(var i=0; i<this.layers.length; ++i){
		var item = this.layers[i].getItemById(id);
		if(item != null){
			return item;
		}
	}
	return null;
}

function gbLayerCtrl(app)
{
	this.init(app);
}

gbLayerCtrl.prototype = new gbLayerGroup();

gbLayerCtrl.prototype.getHTML = function()
{
	var ret ="<table><tr><th>展開</th><th>表示</th><th style='width:200'>レイヤ名</th></tr>";
	if(this.layers != null){
		for(var i=0; i<this.layers.length; ++i){
			ret += this.layers[i].getHTML();
		}
	}
	ret +="</table>";
	return ret;
}


gbLayerCtrl.prototype.update = function()
{
	var obj = getObjectById(this.htmlId);
	if(obj == null){
		// trace("layer control \""+this.htmlId+"\" not found");
		return;
	}
	obj.innerHTML = this.getHTML();
}

gbLayerCtrl.prototype.updateDepth = function(){
	for(var i=0; i<this.layers.length; ++i){
		this.layers[i].updateDepth(0);
	}
}

gbLayerCtrl.prototype.updateByParamStr = function(paramStr){
	// var paramStr = decodeURIComponent(paramStr);
	// trace("gbLayerCtrl.prototype.updateByParamStr called paramStr="+paramStr);
	
	var params = paramStr.split("]");
	var _params = new Array(params.length);
	for(var i=0; i<params.length; ++i){
		_params[i] = params[i].split("[");
	}
	
	for(var i=0; i<this.layers.length; ++i){
		this.layers[i].updateByParams(_params);
	}
}

function gbImageStatus(app){
	this.taskCount = 0;
	this.isDirty = true;
	this.crdStatus = "";
//	this.resourcePath = "";
	this.resetInterval();
	this.app = app;
	this.timeoutId = -1;
	this.isNeedUpdate = false;
}

gbImageStatus.prototype.cancelNextTimeout = function()
{
	// trace("gbImageStatus.prototype.cancelNextTimeout called this.timeoutId="+this.timeoutId);
	if(this.timeoutId != -1){
		window.clearInterval(this.timeoutId);
		this.timeoutId = -1;
	}
}

gbImageStatus.prototype.beginNextUpdateTimer = function()
{
	if(this.isNeedUpdate){
		this.cancelNextTimeout();
		var app = this.app;
		var stat = this;
		this.timeoutId = window.setInterval(
			function(){window.clearInterval(stat.timeoutId); 
			// trace("beginNextUpdateTimer onTimer."); 
			app.updateImage(false);}, 
			this.getNextInterval());
	}
}

gbImageStatus.prototype.resetInterval = function()
{
	this.nextInterval = 100;
}

gbImageStatus.prototype.setNextStatus = function(/*resourcePath,*/ taskCount, isDirty, crdStatus)
{
	this.cancelNextTimeout();
	if(!this.isDirty && !isDirty && (taskCount==0)){
		this.isNeedUpdate = false;
	}
	else{
		this.isNeedUpdate = true;
		if(!this.isDirty && !isDirty){
			if(this.nextInterval<10000){
				this.nextInterval *= 2;
				if(this.nextInterval>10000){
					this.nextInterval = 10000;
				}
			}
		}
		else{
			this.resetInterval();
		}
	}
	
//	this.resourcePath = resourcePath;
	this.taskCount = taskCount;
	this.isDirty = isDirty;
	this.crdStatus = crdStatus;
}

gbImageStatus.prototype.getNextInterval = function()
{
	return this.nextInterval;
}

function gbXPanel(app)
{
	// trace("gbXPanel() created");
	this.app = app;
	this.htmlId = "gbXPanel";
	this.keys = new Array(9);
	for(var i=0; i<9; ++i){
		this.keys[i] = {idx:i, down:new Image(), up:new Image(), state:'up', ctrl:null};
		if(i!=4){
			this.keys[i].up.src = app.getImagesPath()+"ct_btn_"+i+"u.gif";
			this.keys[i].down.src = app.getImagesPath()+"ct_btn_"+i+"d.gif";
		}
		this.keys[i].dx = -(app.imageWidth/2) * (i%3 - 1);
		this.keys[i].dy = -(app.imageHeight/2) * (Math.floor(i/3) - 1);
	}
}

gbXPanel.prototype.initByXML = function(x)
{
	var id = x.getAttribute("htmlId");
	if(id!= null){
		this.htmlId = id;
	}
	this.ctrl = getObjectById(this.htmlId);
	this.ctrl.style.zIndex = 100;
	this.ctrl.innerHTML = this.getHTML();
}

gbXPanel.prototype.getHTML = function()
{
	var ret="<table>";
	for(var i=0; i<3; ++i){
		ret+="<tr>";
		for(var j=0; j<3; ++j){
			ret+="<td style='padding:0'>";
			if(!(i==1&&j==1)){
				var key = this.keys[i*3+j];
				
				ret+="<image id='"+this.getKeyId(i*3+j)+"' src='"+key[key.state].src+"'";
			}
			ret+="</td>";
		}
		ret+="</tr>";
	}
	ret+="</table>";
	return ret;
}

gbXPanel.prototype.getKeyId = function(i)
{
	return this.htmlId+"key"+i;
}

gbXPanel.prototype.initKeyCtrl = function()
{
	if(this.keys[0].ctrl != null){
		return;
	}
	for(var i=0;i<9;++i){
		this.keys[i].ctrl = getObjectById(this.getKeyId(i));
	}
}

gbXPanel.prototype.isContains = function(obj)
{
	this.initKeyCtrl();
	
	for(var i=0;i<9;++i){
		if(this.keys[i].ctrl == obj){
			return true;
		}
	}
	return false;
}

gbXPanel.prototype.onMouseDown = function(obj)
{
	this.initKeyCtrl();
	var key = null;
	for(var i=0;i<9;++i){
		if(this.keys[i].ctrl == obj){
			key = this.keys[i];
		}
	}
	
	if(key == null){
		return;
	}
	
	this.onKeyDown(key);
}

gbXPanel.prototype.onMouseUp = function()
{

}

gbXPanel.prototype.onKeyDown = function(key)
{
	if(this.app.moveImageTo(key.dx, key.dy, key)){
		key.ctrl.src = key.down.src;
	}
}

function gbMark(app, node){
    this.app = app;
    this.node = node;
}
gbMark.prototype = new gbObj();


gbMark.prototype.getImgURL = function(){
    var img = this.node.getAttribute("img");
    var ret = img;
    if(img == null || img == undefined || img == ""){
        return "";
    }
    
	if(img.match(/^((xlp)|(https?))\:\/\//)){
	    return ret;
	}
	else{
		var path = getCurrentPath();
		path = path.substring(0,path.length-1);
	    return path.substring(0, path.lastIndexOf('/')+1) + img;
	}
}

gbMark.prototype.getTransparentColor = function(){
    return this.node.getAttribute("transparentColor");
}


function gbEditableVct(app){
    this.app = app;
	this.id="0";
	this.active = false;
//	this.markImageURL = null;
	this.plotableMarks = null;
}
gbEditableVct.prototype = new gbObj();

gbEditableVct.prototype.initByXML = function(node){
	this.id = node.getAttribute("vctId");
	this.active = (node.getAttribute("active")=="true");
	// this.defaultScheme = node.getAttribute("defaultScheme");
	
	this.plotableMarks = new Array();
    for(var n = node.firstChild; n!=null; n=n.nextSibling){
        if(n.nodeName == "mark"){
            this.plotableMarks.push(new gbMark(this.app, n));
        }
        else if(n.nodeName == "information"){
			this.defaultInfo = n;
		}
    }
    
    if(this.plotableMarks.length == 0){
        alert("[xml error] no plotable mark found in editableVct element. check client_conf.xml");
    }    
    
	// this.markImageURL = node.getAttribute("defaultMarkImage");
}

gbEditableVct.prototype.getId = function(){
	return this.id;
}

gbEditableVct.prototype.setActive = function(b){
	this.active = b;
}

gbEditableVct.prototype.isActive = function(){
	return this.active;
}

gbEditableVct.prototype.getCurrentMark = function(){
    // only 1 mark supported
    return this.plotableMarks[0];
}



function gbApp(){
	this.confXML = null;
	this.target = null;
	this.layerCtrl = null;
	this.move= new gbPoint(0,0);
	this.zoom=1;
	this.rotate=0;
	this.imageName = "image";
	this.loadingStatus = null;
	this.imageLoader = null;
	this.imageObj = null;
	this.imageAnimQueue = new Array();
	this.mode = "rss";
	this.subMode = null;
	this.popupObj = null;
	this.statusCtrl = null;
	this.exParams = null;
	this.oldImageObj = null;
	this.onIdleOperation = null;
	this.isWaitUpdate = false;
	this.currentRequest = null;
	this.clickableMaps = null; // active clickable map 
	this.newClickableMaps = null; // next clickable map 
	this.infoTargetWindow = "gbinfo";
	this.imagesPath = "images/";
	this.cgiPath = "gbgate.cgi";
	this.isEdit = false;
	
	this.abortLevel = gbApp.ABORT_ALL;
	if(gbApp.instances == null){
		gbApp.instances = new Array();
	}
	gbApp.instances.push(this);
	this.id = gbApp.instances.length-1;
	this.modalDialog = null;
	
	this.projectionType = gbApp.PT_LINEAR;
	
	// for edit mode 
	this.sessionId = null;
	this.editableVctAry = [];
	this.activeVct = null;
}

gbApp.ABORT_NONE = 0;
gbApp.ABORT_IMAGE = 1;
gbApp.ABORT_ALL = 2;


gbApp.prototype.getImagesPath = function(){
	return this.imagesPath;
}

gbApp.prototype.getCgiPath = function(){
	return this.cgiPath;
}

gbApp.prototype.onFinishImageAnim = function(arg)
{
	var k = this.imageAnimQueue[0].hilightKey;
	if(k){
		k.ctrl.src = k.up.src;
	}
	
	if(this.imageAnimQueue.length == 1){
		if((this.imageLoader!=null) && this.imageLoader.isComplete()){
			// trace("applyLoadedImage BY onFinishImageAnim");
			this.applyLoadedImage();
		}
		this.imageAnimQueue[0].stop();
	}
	else{
		this.imageAnimQueue[0].destroy();
		delete this.imageAnimQueue[0];
		this.imageAnimQueue.shift();
		this.imageAnimQueue[0].start();
	}
}

gbApp.prototype.setOnIdleOperation = function(eventObj)
{
	this.onIdleOperation = eventObj;
}

gbApp.prototype.moveImageTo_ = function(args)
{
	this.moveImageTo(args[0],args[1],args[2]);
}

gbApp.prototype.getNewAnim = function()
{
	var anim;
	if(this.imageAnimQueue.length==0 || this.imageAnimQueue[0].isActive){
		anim = new divAnim();
		this.imageAnimQueue.push(anim);
	}
	else{
		anim = this.imageAnimQueue[0];
	}
	return anim;
}

gbApp.prototype.moveImageTo = function(xoffset, yoffset, hilight_key)
{
	this.move.x -= xoffset/this.zoom;
	this.move.y -= yoffset/this.zoom;
	
	this.updateImage(true);
	
	
	xdest = -this.move.x*this.zoom+(this.imageWidth-this.imageWidth*this.zoom)/2;
	ydest = -this.move.y*this.zoom+(this.imageHeight-this.imageHeight*this.zoom)/2;
	
	// trace("gbApp.prototype.moveImageTo this.imageObj="+this.imageObj);
	
	var finishAnimHandler = {obj:this, method:"onFinishImageAnim", args:""};
	
	if(this.projectionType == gbApp.PT_LINEAR){
		var anim = this.getNewAnim();
		anim.init(this.imageObj, xdest, ydest, 1, 2*Math.sqrt(xoffset*xoffset+yoffset*yoffset), finishAnimHandler);
		anim.hilightKey = hilight_key;
		this.kickImageAnim();
	}
	else{
		finishAnimHandler.obj[finishAnimHandler.method](finishAnimHandler.args);
	}
	
	return true;
}


function gbGlobalMouseDownHandler(e)
{
	e = (e) ? e : event;
	var obj = e.target ? e.target : e.srcElement;
	if(!gbApp.instances)
		return;
	for(var i=0; i<gbApp.instances.length; ++i){
		gbApp.instances[i].onMouseDown(e,obj);
	}
}

function gbGlobalMouseUpHandler(e)
{
	e = (e) ? e : event;
	var obj = e.target ? e.target : e.srcElement;
	if(!gbApp.instances)
		return;
	for(var i=0; i<gbApp.instances.length; ++i){
		gbApp.instances[i].onMouseUp(e,obj);
	}
}

function gbGlobalMouseMoveHandler(e)
{
	e = (e) ? e : event;
	var obj = e.target ? e.target : e.srcElement;
	
	if(!gbApp.instances)
		return;
	for(var i=0; i<gbApp.instances.length; ++i){
		gbApp.instances[i].onMouseMove(e,obj);
	}
}

gbApp.prototype.applyImageSizeToHtml = function(){
	this.imageObj.style.width = this.imageWidth;
	this.imageObj.style.height = this.imageHeight;
}

gbApp.prototype.initImageByXMLNode = function(node){
trace("gbApp.prototype.initByXML image 2");
	var htmlId = node.getAttribute("htmlId");
trace("gbApp.prototype.initByXML image 3");
	if(htmlId != null){
trace("gbApp.prototype.initByXML image 4");
		this.imageName = htmlId;
trace("gbApp.prototype.initByXML image 5");
	}
trace("gbApp.prototype.initByXML image 6");
	this.imageWidth = parseInt(node.getAttribute("width"));
trace("gbApp.prototype.initByXML image 7");
	this.imageHeight = parseInt(node.getAttribute("height"));
trace("gbApp.prototype.initByXML this.imageName="+this.imageName);
	this.imageObj = getObjectById(this.imageName);
trace("gbApp.prototype.initByXML this.imageObj="+this.imageObj);
	
	this.applyImageSizeToHtml();
	
	var t = node.getAttribute("infoTargetWindow");
	if(t){
		this.infoTargetWindow = t;
	}
}

gbApp.prototype.initByXML = function(x)
{
	this.confXML = x;

// trace("gbApp.prototype.initByXML x.documentElement.childNodes.length="+x.documentElement.childNodes.length);
	if(x.documentElement == null){
		// trace("initByXML: load xml error");
	}
	
	var elements = x.documentElement.childNodes;
	
	for(var i=0; i<elements.length; ++i){
		switch(elements[i].nodeName){
			case "image":
			case "img": // safari
				this.initImageByXMLNode(elements[i]);
				break;
			
			case "layerCtrl":
				this.layerCtrl = new gbLayerCtrl(this);
				this.layerCtrl.initByXML(elements[i]);
				this.layerCtrl.updateDepth();
				break;
			
			case "popup":
				this.popupObj = getObjectById(elements[i].getAttribute("htmlId"));
				break;
			case "xpanel":
				this.xpanel = new gbXPanel(this);
				this.xpanel.initByXML(elements[i]);
				break;
			case "status":
				this.statusCtrl = getObjectById(elements[i].getAttribute("htmlId"));
				break;
				
			case "target":
				this.target = new gbTarget();
				this.target.initByXML(elements[i]);
				break;
			
			case "editableVctCtrl":
				this.setupEditableVctCtrl(elements[i]);
				break;
			default:
		}
	}
	
}


gbApp.prototype.setupEditableVctCtrl = function(ctrlNode)
{
	var html = new Array();
	html.push("<select onchange='theApp.setActiveVct(this.value)'>");
	
	this.editableVctAry = new Array();
	var activeVct=null;
	for(var n=ctrlNode.firstChild; n!=null; n=n.nextSibling){
		if(n.nodeName == "editableVct"){
			
			html.push("<option value='");
			html.push(n.getAttribute('vctId'));
			html.push("'>");
			html.push(n.getAttribute('name'));
			html.push("</option>");
			
			var v = new gbEditableVct(this);
			v.initByXML(n);
			this.editableVctAry.push(v);
			if(v.isActive()){
				activeVct = v;
			}
		}
	}
	html.push("</select>");
	
	if(activeVct!=null){
		this.setActiveVct(activeVct.getId());
	}
	
	var ctrlId = ctrlNode.getAttribute("htmlId");
	
	if(ctrlId){
		var htmlObj = getObjectById(ctrlId);
		if(htmlObj){
			htmlObj.innerHTML = html.join("");
		}
	}
	
}

gbApp.prototype.setActiveVct = function(id){
	for(var i=0; i<this.editableVctAry.length; ++i){
		if(this.editableVctAry[i].getId() == id){
			this.activeVct = this.editableVctAry[i];
			this.activeVct.setActive(true);
		}
		else{
			this.editableVctAry[i].setActive(false);
		}
	}
	
	getObjectById()
}


gbApp.prototype.getQuery = function(mode){
	var ret = new Object();
	if(this.target==null){
		this.target = new gbTarget();
	}
	var target = this.target.toQuery();
	
	var move = this.move.toQuery();
	
	var layer = this.layerCtrl.toQuery();
	var coords = this.layerCtrl.getCoords();
	var coord="";
	for(var i=0; i<coords.length; ++i){
		if(coord != ""){
			coord += "_";
		}
		coord += coords[i].toQuery();
	}
	// trace("target query="+target);
	// trace("move="+move);
	// trace("coord="+coord);
	// trace("layer="+layer);
	
	if(this.exParams!=null){
		for(var p in this.exParams){
			ret[p] = this.exParams[p];
		}
	}
	
	ret.p = "0";
	
	ret.t = target;
	ret.mv = move;
	if(this.rotate != 0){
		ret.r = this.rotate;
	}
	ret.z = this.zoom;
	ret.l = layer;
	if(coord!=""){
		ret.c = coord;
	}
	ret.md = mode;
	ret.s = this.imageWidth + "_" + this.imageHeight;
	
	var debug_on = getObjectById("debug_on");
	if(debug_on && debug_on.checked){
		var host = getObjectById("debug_gbhost");
		ret.host = host.value;
		var port = getObjectById("debug_gbport");
		ret.port = port.value;
		var path = getObjectById("debug_gbpath");
		ret.path = path.value;
	}
	
	return object2queryString(ret);
}

gbApp.prototype.clearOldImage = function()
{
	if(this.oldImageObj!=null){
    	try{
	    	this.getImageWrap().removeChild(this.oldImageObj);
		}
		catch(e){
		    // trace("app.clearOldImage removeChild exception e="+e.toString());
		}
		delete this.oldImageObj;
		this.oldImageObj = null;
	}
}

gbApp.prototype.applyLoadedImage = function()
{
// trace("applyLoadedImage called this.newImageObj="+this.newImageObj);
	this.imageLoader.img = null;
	this.clearOldImage();
	this.oldImageObj = this.imageObj;
	this.imageObj = this.newImageObj;
	this.imageObj.style.left = 0;
	this.imageObj.style.top = 0;
	
	this.clickableMaps = this.newClickableMaps;

	this.setNewParams(this.imageLoader.queryParams);
	
	if(this.onIdleOperation){
		this.onIdleOperation.obj[this.onIdleOperation.method](this.onIdleOperation.args);
		this.onIdleOperation = null;
	}
	else if(this.isWaitUpdate){
		// trace("gbApp.prototype.applyLoadedImage this.isWaitUpdate == true");
		this.updateImage(true);
	}
	else{
		this.imageLoader.imageStatus.beginNextUpdateTimer();
		this.imageLoader.setStatus(gbImageLoader.IDLE);
	}
}

gbApp.prototype.setStatusMsg = function(msg)
{
	if(this.statusCtrl){
		this.statusCtrl.innerHTML = msg;
	}
}

gbApp.prototype.onLoadImage = function()
{
// trace("onLoadImage called");
	
	this.newImageObj = this.imageLoader.img;
	this.newClickableMaps = this.imageLoader.clickableMaps;
	this.imageLoader.clickableMaps = null;
	if(this.imageAnimQueue.length == 0 || !this.imageAnimQueue[0].isActive){
		this.applyLoadedImage();
	}
}

gbApp.prototype.getZoom = function(){
	return this.zoom;
}

gbApp.prototype.kickImageAnim = function(){
	if(!this.imageAnimQueue[0].isActive){
		this.imageAnimQueue[0].start();
	}
}

gbApp.prototype.setZoom = function(mag)
{
	var animTime=800;
	if( (gbPosition.maxReso!=null) && (this.target.position.reso*mag > gbPosition.maxReso) ){
		mag = gbPosition.maxReso/this.target.position.reso;
	}
	
	this.zoom = this.zoom*mag;
	this.updateImage(true);
	
	var anim = this.getNewAnim();
	
	var newWidth = this.imageWidth * this.zoom;
	var x = (this.imageWidth - newWidth)/2 - this.move.x*this.zoom;
	var newHeight = this.imageHeight * this.zoom;
	var y = (this.imageHeight - newHeight)/2 - this.move.y*this.zoom;
	
	anim.init(this.imageObj, x, y, mag, animTime, {obj:this, method:"onFinishImageAnim", args:""});
	this.kickImageAnim();
}

gbApp.prototype.getImageWrap = function()
{
	return getObjectById(this.imageName + "Wrap");
}


gbApp.prototype.getCursorPosOnImage = function()
{
	var wrap = this.getImageWrap();
	var offsetx = this.cursorPos.x - wrap.offsetLeft + getScrollX();
	var offsety = this.cursorPos.y - wrap.offsetTop + getScrollY();
	return {x:offsetx, y:offsety};
}

gbApp.prototype.setDraggingObj = function(obj){
	this.draggingObj = obj;
	
	var x = obj.offsetLeft;
	var y = obj.offsetTop;
	
	this.draggingObj.dragStartPos = new gbPoint(x, y);
	this.draggingObj.dragStartPosApp = new gbPoint(this.cursorPos.x, this.cursorPos.y);
}

gbApp.prototype.onMouseDown = function(e, obj)
{
	var wrap = this.getImageWrap();
	// trace("gbApp.prototype.onMouseDown obj="+obj+" this.imageObj="+this.imageObj);
	
	var infoForm = getObjectById('infoForm');
	for(var n=obj; n; n=n.parentNode){
		if(n == infoForm){
			this.setDraggingObj(infoForm);
			return;
		}
	}
	
	if(this.imageObj == obj || this.oldImageObj == obj || obj == wrap){
		this.onMouseDownImage();
	}
	else if(this.xpanel && this.xpanel.isContains(obj)){
		this.xpanel.onMouseDown(obj);
	}
}

gbApp.prototype.onMouseUp = function(e, obj)
{
	if(this.draggingObj){
		this.draggingObj=undefined;
		return;
	}
	this.xpanel.onMouseUp(obj);
}

gbApp.prototype.onMouseMove = function(e, obj)
{
	this.cursorPos = {x:e.clientX, y:e.clientY};
	
	if(this.draggingObj!=null){
		var newPos = {};
		
		newPos.x = this.draggingObj.dragStartPos.x + (this.cursorPos.x - this.draggingObj.dragStartPosApp.x);
		newPos.y = this.draggingObj.dragStartPos.y + (this.cursorPos.y - this.draggingObj.dragStartPosApp.y);
		this.draggingObj.style.left = newPos.x;
		this.draggingObj.style.top = newPos.y;
		return;
	}
	
	var wrap = this.getImageWrap();
	if(this.imageObj == obj || this.oldImageObj == obj || obj == wrap){
		this.onMouseMoveImage();
	}
}

gbApp.prototype.onMouseMoveImage = function()
{
	var pos = this.getCursorPosOnImage();
	var cursor="default";
	
	var area = this.getAreaAtMouse();
	
	switch(this.mode){
		case 'rss':
		case 'move':
			if(area/* && area.infoXML*/){
				cursor = "pointer";
			}
			else{
				cursor = "move";
			}
		break;
		
		case 'info':
		case 'info2':
		case 'insert':
		case 'update':
		case 'delete':
			{
				if(this.mode == 'insert' || (this.mode== 'update' && this.subMode == 'emove') ){
					cursor = "pointer";
				}
				else{
					if(area){
						if(this.mode == 'update' || this.mode=='delete'){
						    if(area && area.isEditable(this.activeVct.id) ){
							    cursor = "pointer";
						    }
						    else{
    							cursor = "default";
						    }
						}
						else{
						    cursor = "pointer";
						}
					}
					else{
						cursor = "default";
					}
				}
			}
		break;
	}
	this.imageObj.style.cursor = cursor;
	var w = this.getImageWrap();
	w.style.cursor = cursor;
}


gbApp.prototype.getAreaAtMouse = function(){
    if(this.clickableMaps){
        var pos = this.getCursorPosOnImage();
	    return this.clickableMaps.hitTest(pos.x, pos.y);
	}
	else{
	    return false;
	}	
}

function getHtmlByInformation(node){
	var ret='';
	switch(node.nodeType){
		case 1:
		{
			ret = "<table>";
			for(var n=node.firstChild; n; n=n.nextSibling){
				var data = getHtmlByInformation(n);
				ret += "<tr><td nowrap=\"1\">";
				
				//  + (n.nodeName=="#text"?"":n.nodeName) + "</td><td>" + data + "</td></tr>";
				if(n.nodeName == "#text"){
					ret += "";
				}
				else if(n.nodeName == "field"){
					ret += n.getAttribute("name");
				}
				else{
					ret += n.nodeName;
				}
				ret += "</td><td>" + data + "</td></tr>";
			}
			ret += "</table>";
		}
		break;
		
		default:
		{
			var txt = node.nodeValue;
			txt = txt.replace(/</g, "&lt;");
			var re = /(http\:\/\/[a-zA-Z0-9_\-\/\?\.\%\+]+)/g;
			txt = txt.replace(re, "<a href=\"$1\">$1</a>");
			return txt;
		}
	}
	return ret;
}

// {x:destOffsetLeft,y:destOffsetTop])

gbApp.prototype.onMouseDownImage = function()
{
// trace("gbApp.prototype.onMouseDownImage called");

	if(this.imageAnimQueue.length >=1 && this.imageAnimQueue[0].isActive){
		//cancel mouse operation while animate
		return;
	}
	var pos = this.getCursorPosOnImage();
	// trace("onMouseDownImage pos.x="+pos.x+" pos.y="+pos.y);
	
	switch(this.mode){
		case 'insert':
		case 'move':
		case 'rss':
		{
			if(this.mode == 'insert'){
				this.editForm_show('insert', pos);
			}
			else{
			    var area = this.getAreaAtMouse();
    			if(area){
					area.showInfo();
					/*
					area.makeSureDetailLoaded();
					var infoNode = area.infoXML;
					var htmlNode = area.htmlDataNode;
					
					if(infoNode){
						
						var infoTableHead = 
							"<table style=\"width:100%\">"+
							"<tr><th style=\"width:90%\">ポイント情報</th><th>"+
							"<input style=\"width:20\" type=\"button\" value=\"x\" onclick=\"getObjectById('infoForm').style.visibility='hidden'\"/></th>"+
							"</th></tr><tr><td colspan=\"2\">";
						
						var infoTableBody;
						if(htmlNode){
							infoTableBody = getChildrenText(htmlNode);
						}
						else{
							infoTableBody = getHtmlByInformation(infoNode);
						}
						
						var infoTableFoot=
							"</td></tr></table>";
						
						var form = getObjectById('infoForm');
						if(!form){
							alert('infoForm not found in html.');
						}else{
							form.innerHTML = infoTableHead + infoTableBody + infoTableFoot;
							form.style.visibility = 'visible';
						}
						
					}
					else{
						alert("関連した情報は有りませんでした。");
					}
					*/
				}
				else{
			        var destOffsetLeft = this.imageWidth/2 - pos.x;
			        var destOffsetTop = this.imageHeight/2 - pos.y;
				    this.moveImageTo(destOffsetLeft, destOffsetTop);
                }
			}
		}
		break;
		
		case 'info':
		case 'info2':
		{
		    if(this.clickableMaps){
				var area = this.getAreaAtMouse();
				if(area){
					if(area.href == null || area.href==undefined || area.href==""){
						area.makeSureDetailLoaded();
                    	area.showInfo();
					}
					else{
	                    var win = window.open(area.href, this.infoTargetWindow);
					    var app = this;
					    this.focusInfoInterval = window.setInterval(function(){win.focus();clearInterval(app.focusInfoInterval)},10);
				    }
				}
			}
		}
		break;
		
		case 'update':
		case 'delete':
		{
		    if(this.mode == 'update' && this.subMode == 'emove'){
                this.doEditCommand({md:'emove', t:this.target.toQuery(), objCode:this.editingArea.objCode, position:pos.x+"_"+pos.y});
                this.setSubMode(null);
		    }
		    else if(this.clickableMaps){
				var area = this.getAreaAtMouse();
				
				if(area && area.isEditable(this.activeVct.id)){
			        if(this.mode == 'delete'){
						if(!area.makeSureDetailLoaded()){
							return;
						}
			            if(confirm("プロット"+area.getDisplayName()+"を削除してもよろしいですか？")){
			                this.doEditCommand({md:'delete', objCode:area.objCode});
			                return;
			            }
			        }
			        else if(this.mode == 'update'){
    			        this.editingArea = area;
			            this.editForm_show('update', area);
			            return;
			        }
				}
			}
		}
		break;
	}
	
}

gbApp.prototype.onLoadInfo = function(is_success, req, userArg)
{
	// trace("onLoadInfo responseText="+req.responseText);
	
	if(!is_success){
		// trace("load info error.");
		return;
	}
}

gbApp.prototype.infoRequest = function()
{
	var query = this.getQuery('info2');
	// trace("info request quelr="+query);
	
	var req = doRequest(this.getCgiPath()+"?"+query, false);
	if(isResponseOK(req)){
		showPopup(req.responseText, this.popupObj);
	}
	else{
		// trace("infoRequest error.");
	}
}

gbApp.prototype.getCurrentParams = function()
{
	var ret = new Object();
	ret.t = this.target.toQuery();
//	ret.r = this.rotate;
	ret.l = this.layerCtrl.toQuery();
	ret.s = this.imageWidth + "_" + this.imageHeight;
	
	return object2queryString(ret);
}

gbApp.prototype.updateCurentURL = function()
{
	var obj = getObjectById("gbCurentURLTextBox");
	if(!obj){
		return;
	}
	
	if(this.move.x != 0 || this.move.x != 0 || this.zoom != 1){
		return;
	}
	
	var q = getCurrentPath() + "main.cgi?" + this.getCurrentParams();
	if(obj.value != q){
		obj.value = q;
	}
}

gbApp.prototype.onUnload = function(){
	this.setCookie();
}

gbApp.prototype.setCookie = function()
{
	document.cookie = "lastAccessParam="+encodeURIComponent(this.getCurrentParams())+";";
	document.cookie = "cookiedURL="+encodeURIComponent(document.location)+";";
}

gbApp.prototype.initByCookie = function()
{
	if(document.cookie){
		var lastAccessParam;
		var cookiedURL;
		
		var vars = document.cookie.split(/; ?/);
		for(var i=0; i<vars.length; ++i){
			var value = vars[i].split("=");
			value[1] = decodeURIComponent(value[1]);
			if(value.length==2){
				switch(value[0]){
					case "lastAccessParam":
						lastAccessParam = value[1];
					break;
					case "cookiedURL":
						cookiedURL = value[1];
					break;
				}
			}
		}
		
		if( (cookiedURL == document.location) && lastAccessParam && lastAccessParam!=""){
			this.initByAccessParam(lastAccessParam);
			document.cookie = "lastAccessParam=;";
			return;
		}
	}
}

gbApp.prototype.execTrackBack = function()
{
	var ua = navigator.userAgent.toUpperCase();
//	if(ua.match(/MSIE/) && ua.match(/WINDOWS/)){
//	if(!ua.match(/SAFARI/)){
		document.location = this.cgiPath.replace("gbgate\.cgi", "trackback.cgi") + "?param="+encodeURIComponent(this.getCurrentParams());
//	}
}

gbApp.prototype.getTrackBackText = function()
{
	var path = this.cgiPath.replace("gbgate\.cgi", "getgburl.cgi");
	var ret = '<trackback>' + doGetText(path) + '?' + escapeForXML(this.getCurrentParams()) + '</trackback>';
	return ret;
}

gbApp.prototype.updateImage = function(isAbortCurrent){
	// trace("gbApp.prototype.updateImage called isAbortCurrent="+isAbortCurrent);
	var oldImageStatus=null;
	
	if(this.imageLoader != null && this.imageLoader.isActive()){
		if(isAbortCurrent){
			// trace("gbApp.prototype.updateImage last updateImage was aborted");
			oldImageStatus = this.imageLoader.imageStatus;
			this.imageLoader.abort();
			delete this.imageLoader;
			this.imageLoader = null;
		}
		else{
			// trace("updateImage called while updating");
			this.isWaitUpdate = true;
			return;
		}
	}
	else{
		this.clearOldImage();
		if(this.imageLoader){
			oldImageStatus = this.imageLoader.imageStatus;
		}
	}
	this.isWaitUpdate = false;
	this.updateCurentURL();
	this.imageLoader = new gbImageLoader(this, this.getQuery('rss_short'), oldImageStatus);
	/*
	var app = this;
	this.imageLoader.onStatusMsg = function(msg){
		app.setStatusMsg(msg);
	}
	this.imageLoader.onBeginLoadImage = function(img){
		img.className = "image_style";
		app.imageObj.style.zIndex = 1;
		img.style.zIndex = 2;
		img.style.left = -app.imageWidth;
		app.getImageWrap().appendChild(img);
	}
	this.imageLoader.onCompleteLoadImage = function(img){
// trace("this.imageLoader.onCompleteLoadImage called");
		app.onLoadImage();
	}
	this.imageLoader.onAbortLoadImage = function(img){
		// trace("onAbortLoadImage this.state="+this.state + " img="+img);
		if(img){
			app.getImageWrap().removeChild(img);
		}
	}
	*/
	this.imageLoader.start();

}





gbApp.prototype.setMode = function(mode)
{
    this.subMode = null;
	this.mode = mode;
}

gbApp.prototype.setSubMode = function(subMode)
{
    this.subMode = subMode;
}


gbApp.prototype.setNewParams = function(params)
{
	this.move.x = 0;
	this.move.y = 0;
	this.rotate = 0;
	this.zoom = 1;
	
	if(this.exParams!=null){
		delete this.exParams;
		this.exParams = null;
	}
	this.exParams = new Object();
	
	// trace("gbApp.prototype.setNewParams params.length="+params.length);
	for(var i=0; i<params.length; ++i){
		var param = params[i];
		// trace("param[0]="+param[0]+ " param[1]="+param[1]);
		switch(param[0]){
			case 'z':
				this.zoom = parseInt(param[1]);
				break;
			case 's':
				{
					var size = param[1].split('_');
					this.imageWidth = parseInt(size[0]);
					this.imageHeight = parseInt(size[1]);
					this.applyImageSizeToHtml();
				}
				break;
			case 't':
				this.target.updateByParamStr(param[1]);
				break;
			case 'l':
// don't update layer visible by server response
//				this.layerCtrl.updateByParamStr(param[1]);
				break;
			default:
				this.exParams[param[0]] = param[1];
				break;
		}
	}
	return params;
}


gbApp.prototype.initByAccessParam = function(paramStr){
	if(paramStr==null || paramStr==""){
		return;
	}
	
	var isLayerSettingExists=false;
	var params = paramStr.split('&');
	for(var i=0;i<params.length; ++i){
		params[i] = params[i].split('=');
		params[i][1] = decodeURIComponent(params[i][1]);
		switch(params[i][0]){
			case "l":
				this.layerCtrl.updateByParamStr(params[i][1]);
				isLayerSettingExists=true;
			break;
		}
	}
	
	if(!isLayerSettingExists){
		this.layerCtrl.updateByParamStr("");
	}
	
	this.setNewParams(params);
}

/*
gbApp.prototype.editResponse_update(elements){
	alert("[debug]update response called");
}

gbApp.prototype.editResponse_delete(elements){
	alert("[debug]delete response called");
}

gbApp.prototype.editResponse_save(elements){
	alert("[debug]save response called");
}
*/

gbApp.prototype.setEdit = function(){

	var result = this.doEditCommand({md:'open'});
	if(result != null){
		this.isEdit = true;
		
		var sessionNode = xmlFindChildElement(result, 'session');
		if(sessionNode){
			alert(" debug ");
			this.sessionId = sessionNode.getAttribute('id');
			alert(" debug this.sessionId="+this.sessionId);
		}
	}
	
}


gbApp.prototype.doEditCommand = function(params){
	if(this.sessionId){
	    params.sessionId = this.sessionId;
	}
	if(this.activeVct){
		params.vct = this.activeVct.getId();
	}
	var ret = this.doCommand(params, "POST", false);
	if(ret){
		this.updateImage();
		return ret.documentElement;
	}
	else{
		return null;
	}
}

function gbCheckHttpResponse(req)
{
	var code = gbGetHttpStatusCode(req);
	if(code != 200){
		throw ("GLOBALBASE server error. http status code="+code+"\n---response---\n"+req.responseText);
	}
}

gbApp.prototype.checkCommandResponse = function(req)
{
	// trace("doCommand server response="+req.responseText);
	
	if(!isResponseOK(req)){
		throw "doCommand request error.";
	}
	
	gbCheckHttpResponse(req);
	
	var x = req.responseXML;
	if(x.documentElement==null){
		throw  "server error response \n"+req.responseText;
	}
	if(x.documentElement.nodeName != "gvha-status"){
		throw "root node was not \"gvha-status\". \n"+req.responseText;
	}
	
	var resultNode = xmlFindChildElement(x.documentElement, 'result');
	if(!resultNode){
		throw "command result not found";
	}
	
	var type = resultNode.getAttribute('type');
	if(type != 'ok'){
		if(GB_MESSAGES[type]==undefined){
			throw "undefined result type. type="+type+" errorMessage="+getChildrenText(resultNode);
		}
		else{
			throw GB_MESSAGES[type]+"("+type+")"+getChildrenText(resultNode);
		}
	}
}

gbApp.prototype.doCommand = function(params, method, async){
	var req = getRequest();
	req.open(method, this.getCgiPath(), async);
	req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	
	var paramStr='';
	for(param in params){
		if(paramStr!=''){
			paramStr+='&';
		}
		paramStr+=param + '=' + encodeURIComponent(params[param]);
	}
	
	// trace("doCommand paramStr="+paramStr);
	req.send(paramStr);
	
	if(!async){
		try{
			this.checkCommandResponse(req);
		}
		catch(e){
			trace(e);
			alert(e);
			return null;
		}
	}
	return req;
}


gbApp.prototype.editForm_show = function(type, param)
{
    try{
	    var form = new gbEditFormPlot(this, type, param);
	    form.show();
	    this.modalDialog = form;
	}catch(e){
	    alert(e.toString());
	}
}

gbApp.prototype.editForm_addItem = function(){
	this.modalDialog.addItem(true);
}

gbApp.prototype.editForm_deleteItem = function(caption){
	this.modalDialog.deleteItem(caption);
}

gbApp.prototype.editForm_close = function(btn){
	this.modalDialog.close(btn);
}

// ProjectionTypes (for gb:status-projection-type)
gbApp.PT_LINEAR = 1;
gbApp.PT_SPHERE = 2;

function gbImageLoader(app, query, imageStatus){
	this.app = app;
	this.query = query;
	this.state = gbImageLoader.IDLE;
	if(imageStatus){
		this.imageStatus = imageStatus;
	}
	else{
		this.imageStatus = new gbImageStatus(app);
	}
	this.iamgeWidth = 100;
	this.iamgeHeight = 100;
	this.img = null;
	this.reqObj = null;
	this.imageQueryStr = null;
	this.queryParams = null;
	this.clickableMaps = null;
}
gbImageLoader.prototype = new gbObj();

gbImageLoader.IDLE = "待機";
gbImageLoader.LOADING_RSS = "RSS取得中";
gbImageLoader.LOADED_RSS = "RSS取得完了";
gbImageLoader.LOADERR_RSS = "RSS取得失敗";
gbImageLoader.LOADING_IMAGE = "画像取得中";
gbImageLoader.LOADED_IMAGE = "画像取得完了";
gbImageLoader.loadingImages = [];

gbImageLoader.prototype.setQuery = function(query)
{
	this.query = query;
}

gbImageLoader.prototype.isActive = function()
{
	if(this.state == gbImageLoader.IDLE){
		return false;
	}
	return true;
}

gbImageLoader.prototype.start = function()
{
	this.setStatus(gbImageLoader.LOADING_RSS);
	trace("get rss request query="+this.query);
	this.reqObj = doAsyncRequest(this.getApp().getCgiPath()+"?"+this.query, {obj:this, method:"onLoadRSS", args:""});
}

gbImageLoader.prototype.setStatus = function(state){
	this.state = state;
	this.onStatusMsg(state);
}

// for over ride by client program
gbImageLoader.prototype.onStatusMsg = function(msg){
	
}


gbImageLoader.prototype.onLoadRSS = function(is_success, req, userArg)
{
	if(!is_success){
		this.setStatus(gbImageLoader.LOADERR_RSS);
		trace("load rss aborted or error. readyState="+req.readyState+" status="+req.status);
		return;
	}
	if(req.readyState != 4){
		// aborted response
		return;
	}
	try{
		gbCheckHttpResponse(req);
	}
	catch(e){
		trace(e);
		alert(e);
		return;
	}
	
	// trace("gbImageLoader.onLoadRSS responseText.length="+req.responseText.length);
	trace("RESPONSE RSS FILE ="+req.responseText);
	
	var x = req.responseXML;
	if(x.parsed!=undefined && x.parsed==false){
		// trace("### wait xml parsed ");
		var loader = this;
		var timeoutid;
		timeoutid = window.setTimeout(function(){loader.onLoadRSS(is_success, req, userArg); window.clearTimeout(timeoutid);}, 0);
		return;
	}

	this.setStatus(gbImageLoader.LOADED_RSS);
	var images = getElementsByTagName_alt(x, RDF_NS, "li");
	// trace("images.length="+images.length);
	if(images.length == 0){
		alert("rdf:li not found in server response rss.");
		return;
	}
	
	var resource = xmlGetAttributeNS(images[0], RDF_NS, "resource");
	
	var projectionType = getElementsByTagName_alt(x, GB_NS, "status-projection-type");
	if(projectionType && projectionType.length>0){
		this.app.projectionType = Number(getChildrenText(projectionType[0]));
	}
	
	// trace("resource="+resource);
	var items = getElementsByTagName_alt(x, null, "item");
	for(var i=0; i<items.length; ++i){
		var rdfAbout = xmlGetAttributeNS(items[i], RDF_NS, "about");
		
		if(rdfAbout == resource){
			var stat1 = getElementsByTagName_alt(items[i], GB_NS, "status1");
			
			var taskCount = Number(getChildrenText(stat1[0]));
			
			var stat2 = getElementsByTagName_alt(items[i], GB_NS, "status2");
			var isDirty = (Number(getChildrenText(stat2[0])) == 1);
			
			var stat3 = getElementsByTagName_alt(items[i], GB_NS, "status3");
			var crdStatus="";
			if(stat3.length!=0){
				crdStatus = getChildrenText(stat3[0]);
			}
			
			var map_xml = getElementsByTagName_alt(items[i], GB_NS, "html-map");
			if(map_xml.length!=0){
				this.clickableMaps = new gbClickableMaps(this.app);
				this.clickableMaps.initByXML(map_xml[0]);
			}
			
			// trace("taskCount="+taskCount+ " crdStatus="+crdStatus+ " isDirty="+isDirty);
			this.imageStatus.setNextStatus(taskCount, isDirty, crdStatus);
			
			break;
		}
	}
	
	// for safari bug?
	resource = resource.replace(/\&\#38\;/g, "&");
	
	var pos = resource.indexOf("?");
	this.imageQueryStr="";
	if(pos != -1){
		this.imageQueryStr = resource.substring(resource.indexOf("?")+1);
	}
	
	var params = this.imageQueryStr.split("&");
	
	for(var i=0; i<params.length; ++i){
		params[i] = params[i].split("=");
		var param = params[i];
//		param[1] = decodeURIComponent(param[1]);
		switch(param[0]){
			case 't':
				this.target = new gbTarget();
				this.target.updateByParamStr(param[1]);
				break;
			case 's':
				var size = param[1].split('_');
				this.iamgeWidth = parseInt(size[0]);
				this.iamgeHeight = parseInt(size[1]);
				break;
		}
	}
	
	this.queryParams = params;
	
	
	var is_complete_forced=false;
	
	// don't use cache while edit mode
	if(!this.app.isEdit){
		if(this.imageStatus.isDirty==false && this.imageStatus.taskCount==0){
			// force complete image
			resource +="&p=1";
			is_complete_forced=true;
		}
		else if(params!=null && params["p"]==1){
			is_complete_forced=true;
		}
	}
	
	
	if(!is_complete_forced){
		// for no cache
		if(pos==-1){
			resource += "?n="+(new Date()).getTime();
		}else{
			resource += "&n="+(new Date()).getTime();
		}
	}

//	this.onBeginLoadImage(this.img);
	this.img = this.createNewImage();
	
	var loader = this;
	attachImgEvent(this.img, function(){
		if(loader.img!=null){
			loader.setStatus(gbImageLoader.LOADED_IMAGE);
			loader.onCompleteLoadImage(this);
			this.onload=null;
		}
	},function(){alert("error loading image");});
	// trace("resource=    "+resource);
	this.img.src = resource;
	this.setStatus(gbImageLoader.LOADING_IMAGE);
	
}

/*private*/
gbImageLoader.prototype.clearReqObj = function()
{
	delete this.reqObj;
	this.reqObj = null;
}

gbImageLoader.prototype.abort = function()
{
	if(this.reqObj!=null){
		this.reqObj.abort();
		this.clearReqObj();
	}
	
	// trace("gbImageLoader.prototype.abort called");
	
	if(this.state != gbImageLoader.LOADED_IMAGE){
		this.onAbortLoadImage(this.img);
	// trace("gbImageLoader.prototype.abort called 2");
		if(this.img != null){
			this.img.onload = null;
			delete this.img;
			this.img = null;
		}
	}
	
	// trace("gbImageLoader.prototype.abort exit this.img="+this.img);
}

gbImageLoader.prototype.isComplete = function()
{
	if(this.img == null){
		return false;
	}
	return this.img.complete;
}

gbImageLoader.prototype.onStatusMsg = function(msg){
	this.app.setStatusMsg(msg);
}

gbImageLoader.prototype.createNewImage = function(){
	
	var img = document.createElement("img");
	img.style.width = this.iamgeWidth;
	img.style.height = this.iamgeHeight;
	img.className = "image_style";
	this.app.imageObj.style.zIndex = 1;
	img.style.zIndex = 2;
	img.style.left = -this.app.imageWidth;
	this.app.getImageWrap().appendChild(img);
	return img;
}

gbImageLoader.prototype.onCompleteLoadImage = function(img){
	// trace("this.imageLoader.onCompleteLoadImage called");
	this.app.onLoadImage();
}

gbImageLoader.prototype.onAbortLoadImage = function(img){
	// trace("onAbortLoadImage this.state="+this.state + " img="+img);
	if(img){
		this.app.getImageWrap().removeChild(img);
	}
}

function gbClickableArea(app,node)
{
	this.app = app;
    this.node = node;
    this.name = node.getAttribute("name");
    this.objCode = node.getAttribute("objCode");
    this.href = node.getAttribute("href");
    this.shape = node.getAttribute("shape");
    this.resourceId = node.getAttribute("resource");
    
    var coords = node.getAttribute("coords");
	var coords_ = coords.split(",");
	var l = parseInt(coords_[0]);
	var t = parseInt(coords_[1]);
	var r = parseInt(coords_[2]);
	var b = parseInt(coords_[3]);
	this.rect = new gbRect(l,t,r,b);
	
	this.infoXML = null;
	this.htmlDataNode = null;
	
	this.setupInfoAndHtmlDataByXMLNode(node);
}

gbClickableArea.prototype.setupInfoAndHtmlDataByXMLNode = function(node){
	for(var n=node.firstChild; n!=null; n=n.nextSibling){
	    if(n.nodeName == 'information'){
	        this.infoXML = n;
        }
        else if(n.nodeName == 'htmldata'){
			this.htmlDataNode = n;
		}
	}
}

gbClickableArea.prototype.makeSureDetailLoaded = function(){
	if(!this.infoXML){
		var result = this.app.doCommand({md:'object', objCode:this.objCode, vct:this.resourceId}, 'POST', false);
		if(result == null){
			return false;
		}
		
		var objNodes = getElementsByTagName_alt(result.responseXML, null, 'gvha-object');
		if(objNodes!=null && objNodes.length>0){
			this.setupInfoAndHtmlDataByXMLNode(objNodes[0]);
		}
	}
	return true;
}


gbClickableArea.prototype.isEditable = function(resourceId){
    if(!this.resourceId){
        return false;
    }
    
    if(this.resourceId == resourceId){
        return true;
    }
    else{
        return false;
    }
}

gbClickableArea.prototype.getDisplayName = function(){
    if(this.infoXML){
        var nameNodes = getElementsByTagName_alt(this.infoXML, null, "name");
        if(nameNodes.length!=0){
		    return getChildrenText(nameNodes[0]);
		}
		
		var fieldNodes = getElementsByTagName_alt(this.infoXML, GB_NS, 'field');
		if(fieldNodes.length!=0){
		    for(var i=0; i<fieldNodes.length; ++i){
			    if(fieldNodes[i].getAttribute('name') == 'name'){
			    	return getChildrenText(fieldNodes[i]);
			    }
			}
		}
		
    }
    return this.name;
}


gbClickableArea.prototype.hitTest = function(x,y){
    return this.rect.hitTest(x,y);
}

gbClickableArea.prototype.showInfo = function()
{
	this.makeSureDetailLoaded();
	
	if(this.infoXML){
		
		var infoTableHead = 
			"<table style=\"width:100%\">"+
			"<tr><th style=\"width:90%\">ポイント情報</th><th>"+
			"<input style=\"width:20\" type=\"button\" value=\"x\" onclick=\"getObjectById('infoForm').style.visibility='hidden'\"/></th>"+
			"</th></tr><tr><td colspan=\"2\">";
		
		var infoTableBody;
		if(this.htmlDataNode){
			infoTableBody = getChildrenText(this.htmlDataNode);
		}
		else{
			infoTableBody = getHtmlByInformation(this.infoXML);
		}
		
		var infoTableFoot=
			"</td></tr></table>";
		
		var form = getObjectById('infoForm');
		if(!form){
			alert('infoForm not found in html.');
		}else{
			form.innerHTML = infoTableHead + infoTableBody + infoTableFoot;
			form.style.visibility = 'visible';
			
			var anchors = getElementsByTagName_alt(form, null, 'a');
			for(var i=0; i<anchors.length; ++i){
				anchors[i].target = this.app.infoTargetWindow;
			}
		}
	}
	else{
		alert("関連した情報は有りませんでした。");
	}
}



function gbClickableMaps(app)
{
	this.app = app;
	this.areas = new Array();
}

gbClickableMaps.prototype.hitTest = function(x,y){
    var len = this.areas.length;
	for(var i=0; i<len; ++i){
		if(this.areas[i].hitTest(x,y)){
		    return this.areas[i];
		}
	}
	return null;
}

gbClickableMaps.prototype.initByXML = function(x)
{
	for(var n=x.firstChild; n!=null; n=n.nextSibling){
		if(n.nodeName == "area"){
		    this.areas.push(new gbClickableArea(this.app, n));
		    
		    /*
			var name = n.getAttribute("name");
			var shape = n.getAttribute("shape");
			var coords = n.getAttribute("coords");
			var url = n.getAttribute("href");
			if(shape != "rect"){
				alert("click map not support shape="+shape);
				break;
			}
			
			var coords_ = coords.split(",");
			var l = parseInt(coords_[0]);
			var t = parseInt(coords_[1]);
			var r = parseInt(coords_[2]);
			var b = parseInt(coords_[3]);
			
			this.areas.push({left:l, top:t, right:r, bottom:b, href:url});
			*/
		}
	}
}

gbClickableMaps.prototype.setParent = function(node)
{
	for(var i=0; i<this.areas.length; ++i){
		node.appendChild(this.areas[i]);
	}
}

function gbEditFormPlot(app, type, param){
	this.app = app;
	this.type = type;
	this.visible = false;
	
	this.htmlId = 'editForm';
	
	var emoveButton = getObjectById('editForm_emoveButton');

	if(type == 'insert'){
		this.point = new gbPoint(param.x, param.y);
		/*
		this.addItem(true,"name", "");
		this.addItem(true,"url", "");
		this.scheme = app.activeVct.defaultScheme;
		*/
		this.setupItemsByInfoXML(app.activeVct.defaultInfo);
		emoveButton.style.visibility = 'hidden';
	}
	else if(type == 'update'){
        this.point = null;
        var area = param;
        this.area = area;
        this.area.makeSureDetailLoaded();
        if(area.infoXML == null){
			this.setupItemsByInfoXML(app.activeVct.defaultInfo);
		}
		else{
			this.setupItemsByInfoXML(area.infoXML);
        }
        emoveButton.style.visibility = 'inherit';
    }
    else{
        throw "invalid dialog type type="+type;
    }
	
}

gbEditFormPlot.prototype = new gbObj();


gbEditFormPlot.prototype.setupItemsByInfoXML = function(infoXML)
{
	this.scheme = infoXML.getAttribute("scheme");
	this.setAnchorByXML(null);

	for(var node = infoXML.firstChild;
        node!=null; node=node.nextSibling){
		
		if(node.nodeType == 1){
            for(var child = node.firstChild;
                child != null;
                child = child.nextSibling){
                if(child.nodeType == 1){
                    throw ("対応していない形式のinformationが設定されています。 information="+getChildrenText(infoXML));
                }
            }
            
            var fieldName;
            if(node.nodeName == "field"){
				fieldName = node.getAttribute('name');
			}
			else if( (node.nodeName == "anchor") || (node.nodeName == "a") ){
				this.setAnchorByXML(node);
				continue;
			}
			else{
				fieldName = node.nodeName;
			}
            this.addItem(
            	true,
            	fieldName,
            	getChildrenText(node),
            	node.getAttribute('visible'),
            	node.getAttribute('href'),
            	node.getAttribute('media'));
        }
    }
}

gbEditFormPlot.prototype.setAnchorByXML = function(anchorNode){
	var tbody = getObjectById("editFormTbody");
	var inputs = getElementsByTagName_alt(tbody, null, "input");
	for(var i=0; i< inputs.length; ++i){
		if(inputs[i].name == "anchor"){
			if(anchorNode){
				inputs[i].value = getChildrenText(anchorNode);
			}
			else{
				inputs[i].value = "";
			}
			break;
		}
	}
}
			

gbEditFormPlot.prototype.show = function(){
	var obj = getObjectById(this.htmlId);
	obj.style.visibility = 'visible';
	this.visible = true;
}

gbEditFormPlot.prototype.getInfoXML = function()
{
	var information = '<information';
	if(this.scheme){
		information += " scheme=\""+this.scheme+"\"";
	}
	information += '>';
	
	var fieldName;
    var tbody = getObjectById('editFormTbody');
    var inputs = getElementsByTagName_alt(tbody, null, 'input');
	var selects = getElementsByTagName_alt(tbody, null, 'select');
	
	
	for(var i=0; i<inputs.length; ++i){
    	if(inputs[i].name == "anchor"){
			if(inputs[i].value != ""){
				information += "<anchor>"+escapeForXML(inputs[i].value)+"</anchor>";
			}
		}
    }
    
    for(var i=0; i<inputs.length; ++i){
        var inp = inputs[i];
        var inputName = inp.name;
        if(!inputName){
			continue;
		}
		else if(inputName.indexOf('fieldName') == 0){
			var itemID = inputName.substr('fieldName'.length, inputName.length);
			var fieldValue;
			var fieldName = inp.value;
			var href = null;
			
			var visible = 'off';
			var media = 'off';
			
			for(var j=0; j<inputs.length; ++j){
				if(inputs[j].name == 'fieldValue' + itemID){
					fieldValue = escapeForXML(inputs[j].value);
				}
				if(inputs[j].name == 'href' + itemID){
					href = escapeForXML(inputs[j].value);
				}
			}
			for(var j=0; j<selects.length; ++j){
				if(selects[j].name == 'visible' + itemID){
					visible = escapeForXML(selects[j].value);
				}
				if(selects[j].name == 'media' + itemID){
					media = escapeForXML(selects[j].value);
				}
			}
			
			information += "<field name=\"" + fieldName + "\"";
			
			information += " visible=\""+visible+"\"";
			if(href!=null){
				information += " href=\""+href+"\"";
			}
			information += " media=\""+media+"\"";
			
			information += ">";
			information += (fieldValue==null?"":fieldValue);
			information += "</field>";
			
        }
    }
	information += "</information>";
	return information;
}

gbEditFormPlot.prototype.close = function(btn){
    
	if(btn == 'ok'){
	    var information = this.getInfoXML();
	    trace("gbEditFormPlot information="+information);
	    var app = this.getApp();
    	
    	var mark = app.activeVct.getCurrentMark();
    	var params = 
	        {
                md:this.type,
                t:app.target.toQuery(),
                information:information,
                markImg:mark.getImgURL(),
                markTransparent:mark.getTransparentColor()
            };
        if(this.type == 'insert'){
            params.position = this.point.x+"_"+this.point.y;
        }
        else if(this.type == 'update'){
			params.objCode = this.area.objCode;
		}
		
        var result = app.doEditCommand(params);
        if(result==null){
	        // some error
	    }
	    else{
	        app.updateImage(true);
	    }
	}
	else if(btn=='emove'){
	    var app = this.getApp();
    	app.setSubMode('emove');
	}
	
	this.clearFields();
	
    var obj = getObjectById(this.htmlId);
	obj.style.visibility = 'hidden';
	this.visible = false;
	
}

gbEditFormPlot.prototype.clearFields = function()
{
	var tbody = getObjectById("editFormTbody");
	for(var i=tbody.rows.length-1; i>=0; --i){
		var inputs = getElementsByTagName_alt(tbody.rows[i], null, 'input');
		for(var j=0; j<inputs.length; ++j){
			if(inputs[j].name.indexOf('fieldName') == 0){
				tbody.deleteRow(i);
				break;
			}
		}
    }
}


gbEditFormPlot.prototype.deleteItem = function(caption){
    var tbody = getObjectById("editFormTbody");
    for(var i=0; i<tbody.rows.length; ++i){
        if(tbody.rows[i].cells[0].innerHTML == caption){
            tbody.deleteRow(i);
        }
    }
}

gbEditFormPlot.prototype.isFieldExists = function(name){
    var tbody = getObjectById('editFormTbody');
    var inputs = getElementsByTagName_alt(tbody, null, 'input');
    for(var i=0; i<inputs.length; ++i){
        if(inputs[i].value == name){
            if(inputs[i].name.indexOf('field')==0 && inputs[i].name.indexOf('Caption')!=-1){
                return true;
            }
        }
    }
    return false;
}

gbEditFormPlot.prototype.addItem = function(hasAttributes, name, value, visible, href, media){
//	alert("addItem hasAttributes"=hasAttributes+" name="+name+" value="+value+" visible="+visible+" href="+href+" media="+media);
    if(!name){
	    name = prompt("項目名を入力して下さい。", "");
	    if(name == null || name == ''){
		    return;
	    }
	    if(this.isFieldExists(name)){
	        alert("既に同じ名前の項目があります。");
	        return;
	    }
	}
    if(this.isFieldExists(name)){
	    return
	}
	if(!visible){
		visible = "off";
	}
	
	if(!media){
		media = "off";
	}
	
	if(!value){
	    value = "";
	}
	
	var caption;
	switch(name){
	    case "name":
	        caption = "名称";
	        break;
	    case "url":
	        caption = "リンク先URL";
	        break;
	    default:
	        caption = name;
	}
	   
	var tbody = getObjectById("editFormTbody");
	if(tbody == null){
		alert("editFormTbody was not found. main.html needs this");
		return;
	}
	var itemCount = tbody.rows.length-2;
	var tr = tbody.insertRow(itemCount);
	itemCount++;
	var colIndex=0;
	var td = tr.insertCell(colIndex++);
	td.innerHTML = caption;
	td = tr.insertCell(colIndex++);
	
	var contentHtml = "<input type=\"hidden\" name=\"fieldName"+itemCount+"\" value=\""+name+"\"><input name=\"fieldValue"+itemCount+"\" value=\""+value+"\">";
	contentHtml += "<select style=\"display:none\" name=\"visible"+itemCount+"\">"+
					"<option "+(visible=='field'?"selected=\"1\"":"")+" value=\"field\">項目名+内容</option>"+
					"<option "+(visible=='on'?"selected=\"1\"":"")+" value=\"on\">内容のみ</option>"+
					"<option "+(visible=='off'?"selected=\"1\"":"")+"value=\"off\">非表示</option></select>";
	td.innerHTML = contentHtml;
	
	/*
	td = tr.insertCell(colIndex++);
	if(hasAttributes){
		td.innerHTML = "<select style=\"display:none\" name=\"visible"+itemCount+"\">"+
			"<option "+(visible=='field'?"selected=\"1\"":"")+" value=\"field\">項目名+内容</option>"+
			"<option "+(visible=='on'?"selected=\"1\"":"")+" value=\"on\">内容のみ</option>"+
			"<option "+(visible=='off'?"selected=\"1\"":"")+"value=\"off\">非表示</option></select>";
	}
	*/
	td = tr.insertCell(colIndex++);
	if(hasAttributes){
		var hrefHtml = "";
		if(media != "off"){
			hrefHtml += "<input type=\"button\" value=\"upload\" onclick=\"gbShowPostFileForm("+itemCount+")\" />";
		}
		if(href!=null){
			hrefHtml += "<input name=\"href"+itemCount+"\" value=\""+href+"\" size=\"40\" />";
		}
		hrefHtml += 
				"<select style=\"display:none\" name=\"media"+itemCount+"\">"+
				"<option "+(media=='off'?"selected=\"1\"":"")+" value=\"off\">off</option>"+
				"<option "+(media=='image'?"selected=\"1\"":"")+" value=\"image\">画像</option></select>";
		
		td.innerHTML = hrefHtml;
	}
}


function gbShowPostFileForm(index)
{
	var postFileForm = getObjectById('postFileForm');
	var postFileForm_index = getObjectById('postFileForm_index');
	postFileForm_index.value = index;
	postFileForm.style.left = theApp.cursorPos.x + getScrollX() - postFileForm.offsetWidth;
	postFileForm.style.top = theApp.cursorPos.y+ getScrollY();
	postFileForm.style.visibility = 'visible';	
}

function gbSetPostedFileName(index, name, isImage){
	var postFileForm = getObjectById('postFileForm');
	postFileForm.style.visibility = 'hidden';
	var tbody = getObjectById("editFormTbody");
	var inputs = getElementsByTagName_alt(tbody, null, 'input');
	var hrefField = "href"+index;
	
	for(var i=0; i<inputs.length; ++i){
		if(inputs[i].name == hrefField){
			inputs[i].value = name;
			break;
		}
	}
	
	if(isImage){
		var selects = getElementsByTagName_alt(tbody, null, 'select');
		for(var i=0; i<selects.length; ++i){
			if(selects[i].name == ("media"+index)){
				selects[i].value = 'image';
				break;
			}
		}
	}
}

function gbGetOS()
{
	var agent  = navigator.userAgent.toUpperCase();
    if (agent.indexOf("MAC") >= 0)
    	return "MAC";
    if (agent.indexOf("WIN") >= 0)
    	return "WINDOWS";
    if (agent.indexOf("X11") >= 0)
    	return "UNIX";
	return "";
}


function gbSetupDownloadDiv(app, targetDivId){
	try{
		gbDownloadDiv(app.getCgiPath()+"?md=getReleaseRSS", targetDivId);
	}
	catch(e){
		trace(e);
		alert(e);
	}
}

function gbDownloadDiv(url, targetDivId){
	gbDownloadDiv.htmlId = targetDivId;
	
	var req = doRequest(url, false);
	
	if(isResponseOK(req)){
		var doc = req.responseXML;
		var channel = getElementsByTagName_alt(doc, null, 'channel');
		gbCheckHttpResponse(req);
		
		gbDownloadDiv.topURL = getChildrenText(getElementsByTagName_alt(channel[0], null, 'link')[0]);
		
		var itemNodes = getElementsByTagName_alt(doc, null, 'item');
		var items = [];
		for(var i=0; i<itemNodes.length; ++i){
			var item = {};
			for(var node = itemNodes[i].firstChild; node != null; node = node.nextSibling){
				if(node.nodeName == "title"){
					item.title = getChildrenText(node);
				}
				else if(node.nodeName == "link"){
					item.link = getChildrenText(node);
				}
				else if(node.nodeName == "description"){
					item.description = getChildrenText(node);
				}
				else if(node.nodeName == "dc:date"||node.nodeName == "date"){
					item.date = getChildrenText(node);
				}
			}
			items.push(item);
		}
		gbDownloadDiv.items = items;
		
		gbDownloadDiv.setupHtml();
		gbDownloadDiv.getSelectBox().onchange = gbDownloadDiv.updateDescription;
	}
}

gbDownloadDiv.getDescriptionDiv = function(){
	return getObjectById(gbDownloadDiv.htmlId+"_description");
}

gbDownloadDiv.getDateDiv = function(){
	return getObjectById(gbDownloadDiv.htmlId+"_date");
}

gbDownloadDiv.getSelectBox = function(){
	return getObjectById(gbDownloadDiv.htmlId+"_select");
}

gbDownloadDiv.getSelectedItem = function(){
	return gbDownloadDiv.items[gbDownloadDiv.getSelectBox().value];
}

gbDownloadDiv.updateDescription = function(){
	var item = gbDownloadDiv.getSelectedItem();
	if(item){
		var d = gbDownloadDiv.getDescriptionDiv();
		if(d){
			d.innerHTML = item.description;
		}
		d = gbDownloadDiv.getDateDiv();
		if(d){
			d.innerHTML = item.date;
		}
	}
}

gbDownloadDiv.setupHtml = function(){
	
	var os = gbGetOS();
	var items = gbDownloadDiv.items;
	var selectedItem=null;
	var selBox = gbDownloadDiv.getSelectBox();
	
	
	for(var i=0; i<items.length; ++i){
		var title = items[i].title.toUpperCase();
		
		var selected = false;
		if(title.indexOf("WINDOWS") >=0 && os == "WINDOWS"){
			selected = true;
		}
		else if(title.indexOf("MAC") >=0 && os == "MAC"){
			selected = true;
		}
		if(selected){
			selectedItem = items[i];
		}
		selBox.options[i] = new Option(items[i].title, i, selected, selected);
	}
	
	if(selectedItem){
		gbDownloadDiv.updateDescription();
	}
}

gbDownloadDiv.doDownload = function(){
	document.location = gbDownloadDiv.getSelectedItem().link;
}


function gbCreateApp(confFile, accessParam, cgiPath, imagesPath)
{
	var app = new gbApp();
	if(cgiPath != undefined){
		app.cgiPath = cgiPath;
	}
	if(imagesPath != undefined){
		app.imagesPath = imagesPath;
	}
	app.initByXML(doGetXML(confFile));
	app.initByAccessParam(accessParam);
	app.initByCookie();
	app.layerCtrl.update();
	return app;
}


function gbGlobalInit()
{
	if(document.addEventListener){
		document.addEventListener("mousedown", gbGlobalMouseDownHandler, true);
		document.addEventListener("mouseup", gbGlobalMouseUpHandler, true);
		document.addEventListener("mousemove", gbGlobalMouseMoveHandler, true);
	}
	else{
		document.onmousedown = gbGlobalMouseDownHandler;
		document.onmouseup = gbGlobalMouseUpHandler;
		document.onmousemove = gbGlobalMouseMoveHandler;
	}
}

gbGlobalInit();