/* Start of http://www.mentorsphere.com/server/comet.js */
/*
 * register the namespace. See Douglas Crockford's site for details.
 * 
 */
//if ( Type.registerNamespace ) {
//	Type.registerNamespace( "UIF.API.Web" );
//} else {
	var UIF = new Object( );
	UIF[ "API" ] = new Object( );
	UIF.API[ "Web" ] = new Object( );
//}
/**
 * A class for working with the comet server.
 * 
 * This will start the listening on the channel and deal with the messages as they come through. You
 * can respond to the messages by linking to the Dispatch Register method The register method must
 * be executed first!
 * 
 * @param un
 *            The user name that was registered using the Actions service
 * @param token
 *            The session token for the current session
 * 
 * @class
 */
UIF.API.Web.CometClient = function( token, un ) {
	this.isListening = false;
	this.sessionToken = token;
	this.userName = un;
	
};

UIF.API.Web.CometClient.prototype = {
	/**
	 * Starts the channel and opens it up so that we can receive messages
	 * 
	 * @member
	 */
	StartListening : function( ) {
		this.isListening = true;
		this.Listen( );
	},
	/**
	 * Stops listening!
	 * 
	 * @member
	 */
	StopListening : function( ) {
		this.isListening = false;
	},
	/**
	 * Performs the listen by opening an AJAX channel to the server and keeps it open until
	 * something comes down the wire
	 */
	Listen : function( ) {
		/*
		 * when we get into the AJAX call below, this will refer to the jQuery object instead. So we
		 * create a local variable that will have scope in the AJAX success method
		 */
		var client = this;
		/*
		 * call the server channel handler. We only connect to the success method but in production,
		 * you should look for failures as well
		 */
		$.ajax( {
			url : "/CometChannel.ashx",
			//url : "/About.aspx",
			/*
			 * This is subject to same origin policy. To perform cross domain, this will need to be
			 * a GET and you will need to use JSONP instead
			 */
			type : "POST",
			//timeout : 5000,
			//async : true,
			//dataType : "json",
			
			/* Identify this as a JSON RPC call */
			beforeSend : function( xhr ) {
			    //xhr.setRequestHeader("Content-Type", "application/json");
				xhr.setRequestHeader("x-json-rpc", "true");
			},
			error: function(xhr, textStatus, errorThrown) {
			    //alert('jquery ajax error: ' + xhr.status + ' - ' + xhr.requestText + ', textStatus: ' + textStatus + ', errorThrown: ' + errorThrown);
			},
		    success : function( response ) {
		        //alert('jquery ajax success');
				var messages = JSON.parse( response );
				if ( messages != null && messages.length > 0 ) {
					var keepListening = client.isListening;
					/* Loop through each message we received */					
					for ( var i = 0; i < messages.length; i++ ) {
						var message = messages[ i ];

						switch ( message.disposition ) {
							case "Heartbeat" :
								/* Nothing happened, we just got a heartbeat message */
								break;
							case "Cancel" :
								/* Stop listening */
								keepListening = false;
								break;
							case "Messages" :
								/*
								 * We got a message, see if anyone wants to deal with it
								 */
								if ( client.Dispatch != null && typeof ( client.Dispatch ) == "function" ) {
									client.Dispatch( message )
								}
								break;
						}
					}
				}
				if ( keepListening ) {
					client.Listen( );
				}
			}
		} );
	},
	/**
	 * We got a precense change message.
	 * 
	 * @param action
	 *            What happened. Valid values are "add" and "remove".
	 * @param message
	 *            The message that was received. The contents will contain the user name of the user
	 *            that either left or logged on
	 */
	OnPresenceChange : null,
	/**
	 * A chat message was received
	 * 
	 * @param message
	 *            The message that we got. The content property will contain the actual message text
	 *            to display
	 */
	OnChatMessage : null,
	/**
	 * Some left or joined a room
	 * 
	 * @param action
	 *            What happened. Valid values are "add" and "remove".
	 * @param message
	 *            The message that was received. The contents will contain the user name of the user
	 *            that either left or logged on. The roomID will contain the room key.
	 */
	OnRoomChange : null,
	/**
	 * A process, likely an XSS call, is asking that dialog be closed.
	 * 
	 * @param message
	 *            The message that we got. The content property will contain the name of the dialog to close
	 */
	OnCloseDialog : null,
	/**
	 * An email notification was received
	 * 
	 * @param message
	 *            The message that we got. The content property will contain the actual message text
	 *            to display
	 */
	OnMailMessageReceived : null,
	Dispatch : function( message ) {
		switch ( message.messageType ) {
			case "Presence" :
				if ( this.OnPresenceChange != null && typeof ( this.OnPresenceChange ) == "function" ) {
					this.OnPresenceChange( "add", message );
				}
				break;
			case "NoPresence" :
				if ( this.OnPresenceChange != null && typeof ( this.OnPresenceChange ) == "function" ) {
					this.OnPresenceChange( "remove", message );
				}
				break;
			case "Chat" :
				if ( this.OnChatMessage != null && typeof ( this.OnChatMessage ) == "function" ) {
					this.OnChatMessage( message );
				}
				break;
			case "JoinRoom" :
				if ( this.OnRoomChange != null && typeof ( this.OnRoomChange ) == "function" ) {
					this.OnRoomChange( "add", message );
				}
				break;
			case "LeftRoom" :
				if ( this.OnRoomChange != null && typeof ( this.OnRoomChange ) == "function" ) {
					this.OnRoomChange( "remove", message );
				}
				break;
			case "CloseDialog" :
				if ( this.OnCloseDialog != null && typeof ( this.OnCloseDialog ) == "function" ) {
					this.OnCloseDialog( message );
				}
				break;
		    case "EmailNotificiation":
				if ( this.OnMailMessageReceived != null && typeof ( this.OnMailMessageReceived ) == "function" ) {
					this.OnMailMessageReceived( message );
				}
				break;
		}
		
	}
};/* End of http://www.mentorsphere.com/server/comet.js */
/* Start of http://www.mentorsphere.com/server/rtc.ashx?proxy */
// This JavaScript was automatically generated by
// Jayrock.JsonRpc.Web.JsonRpcProxyGenerator, Jayrock, Version=0.9.11214.0, Culture=neutral, PublicKeyToken=null
// on Monday, September 06, 2010 at 11:38:09 AM (Eastern Daylight Time)

function RTC(url)
{
    var self = this;
    var m = ["IsUserOnline","SendMessage","SendEmailNotification","GetOnlineMembers","KillClient","CreateRoom","CloseRoom","AddUserToRoom","GetRoomMembers","RemoveUserFromRoom","SendMessageToRoom","system.listMethods","system.version","system.about"];
    var idems = [true,true,true,true,true,true,true,true,true,true,true,true,true,true];
    
    this[m[0]] = function /* IsUserOnline */ (userName, callback)
    {
        if (self.kwargs) return rpc(new Call(0, { userName: userName }, callback));
        return rpc(new Call(0, [ userName ], callback));
    }
    
    this[m[1]] = function /* SendMessage */ (userName, message, callback)
    {
        if (self.kwargs) return rpc(new Call(1, { userName: userName, message: message }, callback));
        return rpc(new Call(1, [ userName, message ], callback));
    }
    
    this[m[2]] = function /* SendEmailNotification */ (userName, message, callback)
    {
        if (self.kwargs) return rpc(new Call(2, { userName: userName, message: message }, callback));
        return rpc(new Call(2, [ userName, message ], callback));
    }
    
    this[m[3]] = function /* GetOnlineMembers */ (callback)
    {
        if (self.kwargs) return rpc(new Call(3, { }, callback));
        return rpc(new Call(3, [ ], callback));
    }
    
    this[m[4]] = function /* KillClient */ (callback)
    {
        if (self.kwargs) return rpc(new Call(4, { }, callback));
        return rpc(new Call(4, [ ], callback));
    }
    
    this[m[5]] = function /* CreateRoom */ (name, members, callback)
    {
        if (self.kwargs) return rpc(new Call(5, { name: name, members: members }, callback));
        return rpc(new Call(5, [ name, members ], callback));
    }
    
    this[m[6]] = function /* CloseRoom */ (id, callback)
    {
        if (self.kwargs) return rpc(new Call(6, { id: id }, callback));
        return rpc(new Call(6, [ id ], callback));
    }
    
    this[m[7]] = function /* AddUserToRoom */ (members, roomID, callback)
    {
        if (self.kwargs) return rpc(new Call(7, { members: members, roomID: roomID }, callback));
        return rpc(new Call(7, [ members, roomID ], callback));
    }
    
    this[m[8]] = function /* GetRoomMembers */ (roomID, callback)
    {
        if (self.kwargs) return rpc(new Call(8, { roomID: roomID }, callback));
        return rpc(new Call(8, [ roomID ], callback));
    }
    
    this[m[9]] = function /* RemoveUserFromRoom */ (userName, roomID, callback)
    {
        if (self.kwargs) return rpc(new Call(9, { userName: userName, roomID: roomID }, callback));
        return rpc(new Call(9, [ userName, roomID ], callback));
    }
    
    this[m[10]] = function /* SendMessageToRoom */ (roomID, message, callback)
    {
        if (self.kwargs) return rpc(new Call(10, { roomID: roomID, message: message }, callback));
        return rpc(new Call(10, [ roomID, message ], callback));
    }
    
    // Returns an array of method names implemented by this service.
    
    this[m[11]] = function /* system.listMethods */ (callback)
    {
        if (self.kwargs) return rpc(new Call(11, { }, callback));
        return rpc(new Call(11, [ ], callback));
    }
    
    // Returns the version server implementation using the major, minor, build and revision format.
    
    this[m[12]] = function /* system.version */ (callback)
    {
        if (self.kwargs) return rpc(new Call(12, { }, callback));
        return rpc(new Call(12, [ ], callback));
    }
    
    // Returns a summary about the server implementation for display purposes.
    
    this[m[13]] = function /* system.about */ (callback)
    {
        if (self.kwargs) return rpc(new Call(13, { }, callback));
        return rpc(new Call(13, [ ], callback));
    }
    
    var url = typeof(url) === 'string' ? url : 'http://www.mentorsphere.com/server/rtc.ashx';
    var nextId = 0;

    function Call(method, params, callback)
    {
        this.url = url;
        this.callback = callback;
        this.proxy = self;
        this.idempotent = idems[method];
        this.request = 
        { 
            id     : ++nextId, 
            method : m[method], 
            params : params 
        };
    }

    function rpc(call)
    {
        return self.channel != null && typeof(self.channel.rpc) === 'function' ?
            self.channel.rpc(call) : call;
    }

    this.kwargs = false;
    this.channel = new JayrockChannel();

    function JayrockChannel()
    {
        this.rpc = function(call)
        {
            var async = typeof(call.callback) === 'function';
            var xhr = newXHR();
            xhr.open('POST', call.url, async, this.httpUserName, this.httpPassword);
            xhr.setRequestHeader('Content-Type', this.contentType || 'application/json; charset=utf-8');
            xhr.setRequestHeader('X-JSON-RPC', call.request.method);
            if (async) xhr.onreadystatechange = function() { xhr_onreadystatechange(xhr, call.callback); }
            xhr.send(JSON.stringify(call.request));
            call.handler = xhr;
            if (async) return call;
            if (xhr.status != 200) throw new Error(xhr.status + ' ' + xhr.statusText);
            var response = JSON.parse(xhr.responseText);
            if (response.error != null) throw response.error;
            return response.result;
        }

        function xhr_onreadystatechange(sender, callback)
        {
            if (sender.readyState == /* complete */ 4)
            {
                try { 
                    sender.onreadystatechange = null; // Avoid IE7 leak (bug #12964)
                } 
                catch (e) { 
                    /* IE 6/Mobile throws for onreadystatechange = null */ 
                }

                var response = sender.status == 200 ? 
                    JSON.parse(sender.responseText) : {};
                
                callback(response, sender);
            }
        }

        function newXHR()
        {
            if (typeof(window) !== 'undefined' && window.XMLHttpRequest)
                return new XMLHttpRequest(); /* IE7, Safari 1.2, Mozilla 1.0/Firefox, and Netscape 7 */
            else
                return new ActiveXObject('Microsoft.XMLHTTP'); /* WSH and IE 5 to IE 6 */
        }
    }
}

RTC.rpcMethods = ["IsUserOnline","SendMessage","SendEmailNotification","GetOnlineMembers","KillClient","CreateRoom","CloseRoom","AddUserToRoom","GetRoomMembers","RemoveUserFromRoom","SendMessageToRoom","system.listMethods","system.version","system.about"];
/* End of http://www.mentorsphere.com/server/rtc.ashx?proxy */
