/*
 * Aerial.js
 *
 * Copyright (C) 2008 FURUHASHI Sadayuki <fr _at_ syuki.skr.jp>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


function Aerial() {
	this.initialize.apply(this, arguments);
}

Aerial._cbseq = 0;
Aerial._oneshot_callback = function(callback) {
	var cbfunc = "__callback" + (Aerial._cbseq++);
	Aerial[cbfunc] = callback;
	return "function(){ Aerial."+cbfunc+".apply(Aerial, arguments); delete Aerial."+cbfunc+"; }";
}

Aerial._idseq = 0;
Aerial._gen_instance_id = function() {
	return Aerial._idseq++;
}
Aerial._define_callback = function(instance_id, name, callback) {
	var cbfunc = "__instance" + instance_id + "__" + name;
	Aerial[cbfunc] = callback;
	return "function(){ return Aerial."+cbfunc+".apply(Aerial, arguments); }";
}

Aerial.prototype = {
	initialize: function(swfurl, div, callback) {
		var self = this;

		var swfid = "aerial_"  + div;
		var init = Aerial._oneshot_callback(function(){
			self._swf_init(swfid);
			if(callback) { callback() };
		});

		swfobject.embedSWF(swfurl, div, "0", "0",
			"9.0.0", "expressInstall.swf",
			{ initialize: init },
			{ menu: "false", bgcolor: "#ffffff" },
			{ id: swfid, name: swfid },
			{ allowScriptAccess: "always" });

		this.instance_id = Aerial._gen_instance_id();
	},

	_swf_init: function(swfid) {
		this.swf = swfobject.getObjectById(swfid);
	},

	loadPolicyFile: function(host, port) {
		this.swf.loadPolicyFile(host, port);
	},

	connect: function(host, port, callback, failed, closed) {
		this.swf.connect(host, port,
				Aerial._oneshot_callback(callback),
				(failed ? Aerial._oneshot_callback(failed) : ""),
				(closed ? Aerial._oneshot_callback(closed) : "")
			);
	},

	setHandler: function(name, callback) {
		this.swf.setHandler(name,
			Aerial._define_callback(this.instance_id, name, callback)
			);
	},

	call: function(name, args, callback) {
		this.swf.call(name, args,
			(callback ? Aerial._oneshot_callback(callback) : "")
			);
	}
};


