/*
	SWT Browser JavaScript Message Library and Utilities

	Provides a symmetric library for passing messages and objects
	between an SWT Browser widget and the page it displays.

	Clients and pages both register listeners that receive messages
	with optional parameters encoded using JSON.
	
	Requires
		core.js
		json.js
		
	Utilities for launching login and registration popups
	
	Copyright (c) 2006 Azureus, Inc. All rights reserved.
*/

/*
	az.msg
	
	Manages a set of Listeners, each bound to a unique key, that
	receive messages sent to that key. Messages are sent from
	the Java client with optional parameters encoded into a JSON string.
*/
az.msg = new function ( ) {
	this.listeners = {};
	
	/* Returns the listener with the key if it exists */
	this.findListener = function ( /*string*/ key ) {
		return this.listeners[key];
	}
	
	/* Returns the listener with the key, creating one if it doesn't exist */
	this.getListener = function ( /*string*/ key ) {
		var listener = this.findListener(key);
		if ( ! listener ) {
			listener = new this.Listener(key);
			this.listeners[key] = listener;
		}
		return listener;
	}
	
	/* Binds the function to the operation for the listener with the key */
	this.listen = function ( /*string*/ key , /*string*/ op , /*function*/ func ) {
		var listener = this.getListener(key);
		listener.listen(op, func);
	}
	
	/* Unbinds the operation for the listener with the key */
	this.unlisten = function ( /*string*/ key , /*string*/ op ) {
		var listener = this.findListener(key);
		if ( listener ) {
			listener.unlisten(op);
		}
	}
	
	/* Removes the listener with the key */
	this.remove = function ( /*string*/ key ) {
		var listener = this.findListener(key);
		if ( listener ) {
			listener.destroy();
			delete this.listeners[key];
		}
	}
	
	/* Dispatches a message to the listener with the key */
	this.dispatch = function ( /*string*/ key , /*string*/ op , /*JSON*/ params ) {
		var listener = this.findListener(key);
		if ( listener ) {
			listener.dispatch(op, params);
		}
		else {
			debug("No listener bound to " + key);
		}
	}
}

/*
	Listener
	
	Manages a set of functions, each bound to a unique operation, that
	receive messages sent to the listener's key and an operation.
*/
az.msg.Listener = function ( /*string*/ key ) {
	this.key = key;
	this.ops = {};
	
	this.listen = function ( /*string*/ op , /*function*/ func ) {
		this.ops[op] = func;
	}
	
	this.unlisten = function ( /*string*/ op ) {
		this.ops[op] = null;
	}
	
	this.dispatch = function ( /*string*/ op , /*JSON*/ params ) {
		var func = this.ops[op];
		if ( func ) {
			// call function with "this" bound to the Listener and "op" and "params" as parameters
			if ( params === undefined ) {
				func.apply(this, [ op ] );
			}
			else {
				func.apply(this, [ op, params ] );
			}
		}
		else {
			debug("No function bound to " + this.key + "." + op);
		}
	}
}

/*
	Listener
	
	Manages a set of functions, each bound to a unique operation, that
	receive messages sent to the listener's key and an operation.
	
	The optional message parameters are encoded into a JSON string
	and sent to the MessageDispatcher in the Java client via the
	SWT Browser's StatusTextListener.
*/
var sequence = 0;

function resetSequence ( ) {
	sequence = 0;
	sendMessage('dispatcher', 'reset-sequence');
}

function sendMessage ( listener , operation , params ) {
	if ( params ) {
		if ( typeof(params) == 'object' ) {
			sendRealMessage(listener + ';' + operation + ';' + JSONUtils.toJSONString(params));
			
		}
		else if ( typeof(params) == 'array' ) {
			sendRealMessage(listener + ';' + operation + ';' + JSONUtils.toJSONString(params));
			
		}
		else {
			firstChar = params.charAt(0);
			if (firstChar == '{' || firstChar == '[') {
				// Some callers send incorrect json formatted strings,
				// parse it here and re-encode it to spec
				jsonParams = JSONUtils.parseJSON(params);
				properParams = JSONUtils.toJSONString(jsonParams);
				sendRealMessage(listener + ';' + operation + ';' + properParams);
			} else {
				// Bad caller! This isn't in JSON format, so just dump it  
				sendRealMessage(listener + ';' + operation + ';' + params);
			}
		}
	}
	else {
		sendRealMessage(listener + ';' + operation);
	}
}

function sendRealMessage ( message ) {
//	alert( message )
	sequence++;
	window.status = 'AZMSG' + ';' + sequence + ';' + message;
	window.status = '';
}

/*
 * Utility functions
 */
function loginAndGoto(url /*the url to go to in case of successful login*/) {
    // Launch Azureus client popup for login.
    var loginurl = "http://" + window.location.host + "/user/LoginPopup.html";
    sendMessage("lightbox-browser", "open-url",
    {"url":loginurl, "title-prefix-verifier":"vuzePage", "redirect-url":url,
     "width":380, "height":280});
}
function registerAndGoto(url /*the url to go to in case of successful registration AND login*/) {
    // Launch Azureus client popup for registration.
    var loginurl = "http://" + window.location.host + "/user/RegisterPopup.html";
    sendMessage("lightbox-browser", "open-url",
    {"url":loginurl, "title-prefix-verifier":"vuzePage", "redirect-url":url,
     "width":460, "height":580});
}
