var BOSH_SERVICE = '/httpbind/';
var connection = null;

var xmpp_jid = '';
var xmpp_nickname = '';
var xmpp_chatjid = '';
var xmpp_retries = 5;

function XMPPlog(msg) 
{
    $('#xmpp_log').append('<div></div>').append(document.createTextNode(msg));
}

function onXMPPStatusChange(status)
{
    if (status == Strophe.Status.CONNECTING) {
    	XMPPlog('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
    	XMPPlog('Strophe failed to connect.');
    	//XMPPjReconnect();
    } else if (status == Strophe.Status.DISCONNECTING) {
    	XMPPlog('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
    	XMPPlog('Strophe is disconnected.');
    	//XMPPjReconnect();
    } else if ((status == Strophe.Status.CONNECTED) || (status == Strophe.Status.ATTACHED)) {
    	XMPPlog('Client is attached/connected with session ' + connection.sid + '.');

    	connection.send($pres().tree());
    	connection.send($pres({from: xmpp_jid, to: xmpp_chatjid})
    						.c('x', {'xmlns': Strophe.NS.MUC})
    						.tree());
    						
    	if (chatsSetup) {
    		chatsSetup();
    	}
    	/*
    	connection.addHandler(onXMPPMessage, null, 'message', null, null,  null); 
    	connection.addHandler(onXMPPPresence, null, 'presence', null, null,  null);
    	// Request room list
    	connection.send($iq({from: xmpp_jid, to: Strophe.getBareJidFromJid(xmpp_chatjid), id: Strophe.getNodeFromJid(xmpp_jid), type: 'get'})
				.c('query', {'xmlns': Strophe.NS.MUC + '#admin'})
				.c('item', {'affiliation': 'member'})
				.tree());
    	*/
    	/*
    	<iq from='crone1@shakespeare.lit/desktop'
    	    id='member3'
    	    to='darkcave@chat.shakespeare.lit'
    	    type='get'>
    	  <query xmlns='http://jabber.org/protocol/muc#admin'>
    	    <item affiliation='member'/>
    	  </query>
    	</iq>
    	*/    	
    }
}

function XMPPjReconnect() {
	// Using AJAX for make new session
	
	if (xmpp_retries > 0) {
	
		$.ajax({
			type: 'POST',
			url: '/chat-reconnect',
			data: {},
			error: function(req, text, error) {
				alert('Ошибка AJAX: ' + text + ' | ' + error);
			},
			success: function (json) {
				if (json[0] == 'success') {
					$.cookie('jid', json[1]);
					$.cookie('sid', json[2]);
					$.cookie('rid', json[3]);
					$.cookie('nickname', json[4]);
					
					XMPPlog("RESTART with: " + $.cookie('rid'));
					
					xmpp_jid = $.cookie('jid'); 
					xmpp_nickname = $.cookie('nickname');
					xmpp_chatjid = 'common@conference.sim-portal.ru/' + xmpp_nickname;
					
					//chatUserList = new XMPPChatUserList(xmpp_chatjid, 'xmpp_list');
					
					if ((xmpp_jid) && ($.cookie('sid')) && ($.cookie('rid'))) {
						connection.attach(xmpp_jid, $.cookie('sid'), $.cookie('rid'), onXMPPStatusChange);
					} else {
						XMPPlog("Can't attach.");
					}
					
				} else {
					// 	Cannot create new session
				}
			},
			dataType: "json"
		});
	
		xmpp_retries --;
	} else {
		// Retries is over
	}
}

/*
function onXMPPMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "chat" && elems.length > 0) {
    	var body = elems[0];
    	
    	$('#xmpp_text').append('<b>' + Strophe.getResourceFromJid(from) + ' (лично)</b>: ' + Strophe.getText(body) + '<br>');
    	
    	if (Strophe.getText(body) == '!wakeup') {
    		var reply = $msg({to: from, from: to, type: 'chat'})
            .c('body', 'Я не сплю, я тут! :)');
    		connection.send(reply.tree());
    		
        	connection.send($iq({from: xmpp_jid, to: Strophe.getBareJidFromJid(xmpp_chatjid), id: Strophe.getNodeFromJid(xmpp_jid), type: 'get'})
    				.c('query', {'xmlns': Strophe.NS.MUC + '#admin'})
    				.c('item', {'affiliation': 'member'})
    				.tree());
       	}
    	
    } else if (type == "groupchat" && elems.length > 0) {
    	var body = elems[0];
    	
    	$('#xmpp_text').append('<b>' + Strophe.getResourceFromJid(from) + '</b>: ' + Strophe.getText(body) + '<br>');
    }

    // we must return true to keep the handler alive.  
    // returning false would remove it after it finishes.
    return true;
}
*/

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);

    // Uncomment the following lines to spy on the wire traffic.
    //connection.rawInput = function (data) { XMPPlog('RECV: ' + data); };
    //connection.rawOutput = function (data) { XMPPlog('SEND: ' + data); };

    // Uncomment the following line to see all the debug output.
    //Strophe.log = function (level, msg) { XMPPlog('LOG: ' + msg); };

/*
    $('#connect').bind('click', function () {
	var button = $('#connect').get(0);
	if (button.value == 'connect') {
	    button.value = 'disconnect';

	    connection.connect($('#jid').get(0).value,
			       $('#pass').get(0).value,
			       onConnect);
	} else {
	    button.value = 'connect';
	    connection.disconnect();
	}
    });
    */

	//XMPPlog("START with: " + $.cookie('rid'));

	Strophe.log = function(level, msg) {
		XMPPlog('L' + level + ': ' + msg);
	}
	
    xmpp_jid = $.cookie('jid') || '';
    xmpp_nickname = $.cookie('nickname') || '';
    xmpp_pass = $.cookie('pass') || '';
    xmpp_chatjid = 'common@conference.sim-portal.ru/' + xmpp_nickname;

	XMPPlog("START for " + xmpp_jid + ' ' + xmpp_pass);
    
	/*
    if ((xmpp_jid) && ($.cookie('sid')) && ($.cookie('rid'))) {
    	connection.attach(xmpp_jid, $.cookie('sid'), $.cookie('rid'), onXMPPStatusChange);
    } else {
    	XMPPlog("Can't attach.");
    }
    */
	
	connection.connect(xmpp_jid, xmpp_pass, onXMPPStatusChange, 30, 1);
});

