/*
 *  craxtop.js: Javascript interface for CR plug-in version 0.0.3 (Apr. 4 2008)
 *  (c) 2008 Splume Corporation.
 *
 *  This script uses Prototype.js (see http://www.prototypejs.org/).
 *
 */

// Load CRObject., see http://www.splume.com/3Dsm/activex/js/crax.js
//function loadCRAX(
//    target, craxid,
//    width, height, bkcolor,
//    cmdpanelStyle,
//    directLogin,
//    stturl,
//    myRoomUserID,
//    communityID,
//    guestFlag);

function AXMsgClient2ContainerDispatch( in_str )
{
	var paramArray = in_str.split(" ");
	var cmd = paramArray.shift();
	var arg = paramArray.join(" ");
	//alert("AXMsgClient2ContainerDispatch()" + " : in_str [" + in_str + "]");
	//alert("cmd:'" + cmd + "' arg:'" + arg + "'");

	if( cmd == "AXOnLoginComplete" ) {
		//ログインが完了した
		if( typeof(AXOnLoginComplete) == "undefined" ) { return; }
		AXOnLoginComplete();
	}
	else if( cmd == "AXOnOpenProfile" ) {
		//プロフィールを開く
		if( typeof(AXOnOpenProfile) == "undefined" ) { return; }
		AXOnOpenProfile(arg);
	}
	else if( cmd == "AXOnBoundaryCrossed" ) {
		//セルの境界を越えた
		if( typeof(AXOnBoundaryCrossed) == "undefined" ) { return; }
		AXOnBoundaryCrossed(arg);
	} else if ( cmd == "AXOpenWindow" ) {
		if( typeof(AXOpenWindow) == "undefined" ) { return; }
		AXOpenWindow(arg);
	} else if ( cmd == "openPopupWindow" ) {
		if( typeof(AXOpenPopupWindow) == "undefined" ) { return; }
		AXOpenPopupWindow(arg);
	} else if( cmd == "AXOnForceLogout" ) {
		AXOnForceLogout();
	} else if( cmd == "rightiframe_jump" ) {
		if( typeof(rightIFrame_jump) == "undefined" ) { return; }
		rightIFrame_jump(arg);
	} else if( cmd == "launchToMyRoom" ) {
		if( typeof(_launchToMyRoom) == "undefined" ) { return; }
		_launchToMyRoom(arg);
	} else if( cmd == "AXOnSnapshotTaken" ) {
		if( typeof(AXOnSnapshotTaken) == "undefined" ) { return; }
		AXOnSnapshotTaken(arg);
	} else if( cmd == "AXOnThumbnailUpdated" ) {
		if( typeof(AXOnThumbnailUpdated) == "undefined" ) { return; }
		AXOnThumbnailUpdated();
	}
}

//プロフィールを開く
function AXOnOpenProfile(whereUserID)
{
    if( (crax == undefined) ) { return; }
    var intUserID = crax.intUserID;
    if( intUserID <= 0)
		return;
	if (whereUserID == 0 || intUserID == whereUserID) {
        callSProfile(intUserID, whereUserID);
	} else {
		var query = Object.toQueryString({
			int_user_id:   intUserID,
			where_user_id: whereUserID
		});
		AXOpenWindow("othersprofile" + " " + query);
    }
}

function AXOnForceLogout()
{
	setTimeout(function () {
			AXOpenWindow("force_logout");
		},
		3000 /* ms */);
}

//セルの境界を越えた
function AXOnBoundaryCrossed(url)
{
    //alert("AXOnBoundaryCrossed(url) : [" + url + "]");
	if( typeof(id) != "undefined" ) {
		id.value = url;
	}
	else if( typeof(cellURLtext) != "undefined" ) {
		cellURLtext.value = url;
	}
	set_cellname_start(url);
//add by tanaka 2008.6.2
	launch_centercolum(url);
//add by tanaka 2008.6.2
}

//add by tanaka 2008.6.2
function launch_centercolum(url)
{
	var intUserID = crax.intUserID;
	var params = $H({
		url : url,
		int_user_id : intUserID
	}).toQueryString();
	var cgi_url = '/_get_centercolum_url';

	var myAjax = new Ajax.Request(
		cgi_url, 
		{
			method: 'get', 
			parameters: params, 
			org_url : url,
			onSuccess: function (httpReq) {
				var weburl = get_weburl_from_aclXML(httpReq);
				if (weburl != "")  {
					update_centercolum(weburl);
				} else {
//					alert("ajax_success:'" + url + "'");
				}
			},
			onFailure: function (httpReq) {
//				alert("ajax_failure:'" + url + "'");
			}
		}
	);

}
function get_weburl_from_aclXML(httpReq)
{
		var res = httpReq.responseXML;
		var taglist = res.getElementsByTagName("centercolum");
		if (taglist.length < 1) {
			return "";
		}
		var url = taglist[0].getAttribute('url');
		return (url != null) ? decodeURIComponent(url) : "";
}
function update_centercolum(weburl){
	top.centerColumn.location.href = weburl;
}
//add by tanaka 2008.6.2

function id_jump()
{
	if( typeof(id) != "undefined" ) {
		launchToCellByURL(id.value);
	}
	else if( typeof(cellURLtext) != "undefined" ) {
		launchToCellByURL(cellURLtext.value);
	}
}

function id_onKeyPress(e)
{
	var keyCode = 0;
	if( (typeof(e.which) != "undefined") && (e.which != null) ) {
		//FireFox
		keyCode = e.which;
	}
	else if( (typeof(event.keyCode) != "undefined") && (event.keyCode != null) ) {
		//IE
		keyCode = event.keyCode;
	}
	if( keyCode == 13 ) {
		id_jump();
    }
}

//呼出メッセージ
function receiveCallMessage(name,  message)
{
    //alert("AXOnCallMessage(name,  message) : [" + name + "], [" + message + "]");
    if( callSender != undefined ) {
		callSender.value = name + "さんより";
	}
    if( callMessage != undefined ) {
		callMessage.value = message;
	}
    if( callIcon != undefined ) {
		callIcon.src = "/images/message_get.gif";
	}
}


//----------------------------------------------------
var loginWaitCount = 0;

function login()
{
	//alert("login()");
	
//	if( (crax == undefined) || ((typeof(crax.AXAutoLogin) == "undefined") && (typeof(crax.AXCRLogin) == "undefined")) ) { return; }
	if( crax == undefined ) {
	//	alert("crax == undefined");
		return 0;
	}
	else if(
		(typeof(crax.AXAutoLogin) == "undefined") && 
		(typeof(crax.AXCRLogin) == "undefined") && 
		(typeof(crax.AXStartConnection) == "undefined") ) {
	//	alert("crax.AXAutoLogin or crax.AXCRLogin or crax.AXStartConnection == undefined");
		return 0;
	}

	var loginResult = -1;
	if( typeof(crax.AXStartConnection) != "undefined" ) {
		var connection = GetCookie("connection");
		//alert("crax.AXStartConnection(connection) : [" + connection + "]");
		if( (connection == null) || (connection == "") ) {
			return 1;
		}
		loginResult = crax.AXStartConnection(connection);
	} else
	if( typeof(crax.AXCRLogin) != "undefined" ) {
		//javascriptからアカウントクッキーを渡してログイン
		var account = GetCookie("account");
		if( (account == null) || (account == "") ) {
			return 1;
		}
		//alert("crax.AXCRLogin(account) : [" + account + "]");
		loginResult = crax.AXCRLogin(account);
	} else {
		//CRプラグインがアカウントクッキーを読んでログイン
		//alert("crax.AXAutoLogin()");
		loginResult = crax.AXAutoLogin();
	}

	if( loginResult != 0 && loginResult != 3) {
		if( loginResult == 5 ) {
			//二重ログイン
			if( loginWaitCount >= 3 ) {
				alert("二重ログインはできません");
				loginWaitCount = 0;
				return -1;
			}
			loginWaitCount += 1;
			setTimeout("login()", 1000 * 5);
			return 2;
		}
		else {
			alert("ログインエラー");
			loginWaitCount = 0;
			return -1;
		}
	}

    return 1;
}

function logout()
{
    if( (crax != undefined) && (typeof(crax.AXLogout) != "undefined") ) { crax.AXLogout(); }
}

//---------
// implementation for utilities

var Cell_last_url = "";
function _launchToCellByURL(url,str)
{
	_launchToCellByURLWithPosition(url, "0 0 0", "0 0 0");
}

function _launchToCellByURLWithPosition(url,position,rotation)
{
	var posArray = position.split(" ");
	var rotArray = rotation.split(" ");

	if( (top.crax != undefined) && (typeof(top.crax.AXSetURLWithRotMov) != "undefined") && (url) ) {
		if (url != top.Cell_last_url) {
			top.setCurrentRoomname('');
			top.Cell_last_url = url;
		}
		top.crax.AXSetURLWithRotMov(url, posArray[0], posArray[1], posArray[2], rotArray[0], rotArray[1], rotArray[2]);
	}
}

function setCurrentRoomname(str)
{
	var element=top.document.getElementById("currentroomname");
//	element.innerHTML= str;
	if( element!=null ) {
		element.value = str;
	}
}

function _getCurrentRoomname()
{
	var element=top.document.getElementById("currentroomname");
//	if (element != null)
//		return element.innerHTML;
	if( element!=null ) {
		return element.value;
	}
	return null;
}

function _getCurrentRoomURL()
{
	return top.Cell_last_url;
}

function set_cellname_start(url) {

	// Space name <= media name if exist(url) in media_tbl

	var params = $H({
		url : url,
		encoding: 'utf-8'
	}).toQueryString();
	var cgi_url = '/_get_space_name';

	var myAjax = new Ajax.Request(
		cgi_url, 
		{
			method: 'get', 
			parameters: params, 
			org_url : url,
			onSuccess: function (httpReq) {
				var str = get_medianame_from_XML(httpReq);
//alert("success:'" + str + "'");
//alert("success:'" + httpReq.responseText + "'");
				if (str != "")  {
					top.Cell_last_url = url;
		                        setCurrentRoomname(str);
				} else {
					set_cellname_from_AX(url);
				}
			},
			onFailure: function (httpReq) {
//alert("failure:'" + str + "'");
				set_cellname_from_AX(url);
			}
		});
}

function set_cellname_from_AX(url)
{
//alert("set_..AX():url:'" + url + "'");
	var str = "";
	if (typeof(top.crax.AXGetCellName) != "undefined") {
		top.Cell_last_url = url;
		str = top.crax.AXGetCellName(url);
	}
	if (str != "") {
		setCurrentRoomname(str.escapeHTML());
	} else {
		var params = $H({
			url : url,
			int_user_id : 1,
			accept_id : 0,
			no_loading : 'yes',
			operation_type: 'edit',
			encoding: 'utf-8'
		}).toQueryString();
		var cgi_url = '/_cell_access';

		var myAjax = new Ajax.Request(
			cgi_url, 
			{
				method: 'get', 
				parameters: params, 
				org_url : url,
				onSuccess: function (httpReq) {
					var str = get_cellname_from_aclXML(httpReq);
//alert("success:'" + str + "'");
//alert("success:'" + httpReq.responseText + "'");
					if (str != "")  {
						top.Cell_last_url = url;
                	    if (url.match(/\/user\/\d\/\d\/\d\/\d\/\d+\//)) {
                        	setCurrentRoomname(str + "さん");
	                    }
        	            else {
                	        setCurrentRoomname(str);
                    	    }
					}
				}
			});
	}
}

function get_cellname_from_aclXML(httpReq)
{
		var res = httpReq.responseXML;
		var taglist = res.getElementsByTagName("cell_access");
		if (taglist.length < 1) {
			return "";
		}
		var url = taglist[0].getAttribute('name');
		return (url != null) ? url : "";
}

function get_medianame_from_XML(httpReq)
{
	var res = httpReq.responseXML;
	var taglist = res.getElementsByTagName("media");
	if (taglist.length < 1) {
		return "";
	}
	var names = taglist[0].getElementsByTagName("name");
	if (names.length < 1) {
		return "";
	}
	var name = names[0].firstChild.nodeValue;
//alert("get_medianame_from_XML: name="+name);
	return name;
}

function addFavorite (intUserId) {
    var query;
	if (typeof (id) == "undefined") {
		var query = Object.toQueryString({
			int_user_id:   intUserId
		});
	} else {
		var query = Object.toQueryString({
			int_user_id:   intUserId,
			cmd: "add"
		});
	}
	AXOpenWindow("favorite" + " " + query);
}

function callSProfile (intUserId, whereUserId) {
    var query = Object.toQueryString({
        int_user_id:   intUserId,
        where_user_id: whereUserId
    });
	//AXOpenWindow("profile" + " " + query);
	AXOpenWindow("space_3d_index");
}

function callSProfile_init (intUserId, whereUserId) {
    var query = Object.toQueryString({
        int_user_id:   intUserId,
        where_user_id: whereUserId
    });
	//AXOpenWindow("profile_init" + " " + query);
	AXOpenWindow("space_3d_index");
}

function callMyRoomCustomizeRight_init (intUserId, whereUserId) {
	var query = Object.toQueryString({
		int_user_id:	intUserId,
		where_user_id:	whereUserId
	});
	AXOpenWindow("myroom_customize_right");
}

var axWindowTbl_sns = {
	"profile_init" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index.jsp?mode=hub&" },
	"profile" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=hub&" },
	"othersprofile" : {target : "centerColumn",
			url: "/_friends_index?" },
	"mail" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=mail&" },
	"friend" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=friends&" },
	"myroom" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=myroom&" },
	"pet" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=pet&" },
	"community" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=commu&" },
	"ashiato" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=ashiato&" },
	"media" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=storage&" },
	"favorite" : {target : "rightIFrame_frame",
			url: "/sprofile/sns/index_frameset.jsp?mode=favorite&" },
	"media_replace" : {target : "rightIFrame_frame",
			url: "/cgi-bin/media_replace/replace.cgi?" },
	"get_room_cell_url" : {
			url: "/_get_room_cell_url" },
	"force_logout" : {target : "top",
			url: "/_lo" },
	"windowOpenTest" : {target : "",
			url: "/s/test.html", option: "" },
//	"call_message" : {target : "rightIFrame_frame",
//			url: "/sprofile/sns/call_message.jsp?" },
//	"friends_request" : {
//			url: "/sprofile/sns/friends_request.jsp" },
//	"hub_edit02" : {target : "rightIFrame_frame",
//			url: "/sprofile/sns/hub_edit02.jsp" },
//	"mypage" : {target : "centerColumn",
//			url: "/_commu_index?" },
	"space_3d_index" : {target : "rightIFrame_frame",
			url: "/_space_3d_index" },
	"myroom_customize_right" : {target : "rightIFrame_frame",
			url: "/_my_room_customize" },
	"dummy" : ""
};

function AXOpenWindow(arg)
{
	var paramArray = arg.split(" ");
	var content = paramArray.shift();
	var cgiParam = paramArray.join(" ");

	var windowInfo = axWindowTbl_sns[content];
	if (windowInfo == undefined) {
alert("content:'" + content + "' cgiParam:'" + cgiParam + "'");
		return;
	}
	var url = windowInfo['url'];
	if (cgiParam != '') {
		url += cgiParam;
	}
	var target = windowInfo['target'];
//alert("url:'" + url + "' target:'" + target + "'");
	if (target == "top") {
		window.location.href = url;
	} else if (typeof($(target)) != "undefined" && $(target) != null) {
		$(target).src = url;
	}

	if (target == "media_replace" && typeof(AXOnMediaReplace) != "undefined" ) {
		AXOnMediaReplace();
	}
}

function AXOpenPopupWindow(arg)
{
	var paramArray = arg.split(" ");
	var content = paramArray.shift();
	var cgiParam = paramArray.join(" ");

	var windowInfo = axWindowTbl_sns[content];
	var url = windowInfo['url'];
	var target = windowInfo['target'];
	var option = windowInfo['option'];
	//alert("url:" + url + ", target:" + target + ", option:" + option);
	window.open( url + cgiParam, target, option );
}

function get_room_cell_url(where_user_id, do_async, func)
{
	var windowInfo = top.axWindowTbl_sns['get_room_cell_url'];
	if (windowInfo == undefined) {
		return "";
	}
	var url = windowInfo['url'];
	var params = $H({
		where_user_id: where_user_id
		}).toQueryString();

	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			asynchronous: do_async, 
			parameters: params,
			onSuccess: function(httpReq) {
				var returl = httpReq.responseText;
				if (!returl.match(/^http:/)) {
					returl = "";
				}
				returl = returl.match(/^.*/);	// chomp
				func(where_user_id, returl);
			},
			onFailure: function (httpReq) {
				func(where_user_id, "");
			}
		});
}

function _launchToMyRoom(int_user_id)
{
	var func = function (where_user_id, url) {
		if (url != "") {
			top.launchToCellByURL(url);
		}
	};
	top.get_room_cell_url(int_user_id, true, func);
}

