


var MediaContainer = {

	loadIframe: function() {
		$('.A_loader').each( function() {
			// このiframeのデフォルトの高さ
			var height = $(this).height();

			// このiframeのソース
			var src = $(this).attr('alt');

			// このiframeに割り当てるid
			var id = $(this).attr('id').replace(/^A_loader_(home|profile|canvas)_/, "A_iframe_$1_");

			// 描画するiframeタグ
			var html = '<iframe id="' + id + '" name="' + id + '" style="width: 100%; height: ' + height + 'px;" src="' + src + '" scrolling="no" frameborder="no"></iframe>';

			// 描画する
			$(this).replaceWith( html );

			var baseUrl = gadgets.rpc.getOrigin(src);
			var serverRpcRelay = '/gadgets/files/container/rpc_relay.html';
			gadgets.rpc.setRelayUrl( id, baseUrl + serverRpcRelay );
			gadgets.rpc.setAuthToken( id, 0 );
		});
	},

	loadSupport: function() {
		$('.A_support').each( function() {
			// このアプリの識別子
			var code = $(this).attr('alt');

			// 呼び出すURL
			// var url = '/appli/osappli/' + code + '/support/';
			var url = '/appli/osappli/' + code + '/support/?rand=' + Math.floor( Math.random() * 1000 );

			// ロードする
			// $(this).load( url, function(){
			// 	// thickboxを起動する
			// 	tb_init('a.thickbox, area.thickbox, input.thickbox');
			// 	imgLoader = new Image();
			// 	imgLoader.src = "/static/js/thickbox/images/loadingAnimation.gif";
			// });
			$(this).load( url );
		});
	},

	setHeight: function( height ) {
		// this.f には iframe の name属性が入っている
		var ifr = $('#' + this.f);
		if( ifr === undefined ) return;

		// 最大値4096px
		if( height > 4096 ) height = 4096;

		// 高さを変更する
		ifr.height( height );

		// 終わり
		return;
	},

	requestNavigateTo: function( view, opt_params ) {
		// this.f には iframe の name属性が入っている
		var ifr = $('#' + this.f);
		if( ifr === undefined ) return;

		// 各ビューごとのリンク先URLを決定する
		var url;

		// home
		if( view == 'home' ) {
			url = '/';

		// profile
		} else if( view == 'profile' ) {
			url = '/';

		// canvas
		} else if( view == 'canvas' ) {
			// IDからこのアプリの識別子を得る
			var code = ifr.attr('id').replace(/^A_iframe_(home|profile|side|canvas)_/, '');
			url = '/appli/osappli/' + code + '/canvas/';

		} else {
			url = '/';
		}

		// クエリを組み立ててURLに追加
		if( opt_params ) {
			var paramStr = $.toJSON(opt_params);
			// if( paramStr.length > 0 ) url += '?appParams=' + encodeURIComponent(paramStr);
			if( paramStr.length > 0 ) url += '?view-params=' + encodeURIComponent(paramStr);
		}

		// 飛ばす
		document.location.href = url;

		// 終わり
		return;
	}
};


gadgets.rpc.register( 'resize_iframe', MediaContainer.setHeight );
gadgets.rpc.register( 'requestNavigateTo', MediaContainer.requestNavigateTo );

$(document).ready(function() {
	MediaContainer.loadIframe();
	MediaContainer.loadSupport();
});




