/**
 *   Copyright (C) 2004-2007 Stefan Strigler <steve@zeank.in-berlin.de>
 *   Copyright (C) 2008 Marcelo Jorge Vieira (metal) <metal@alucinados.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Public License can be found at http://www.gnu.org/copyleft/lgpl.html
 *
 */

var status_img = {
    "unavailable": 'images/iconsets/'+iconTheme+'/unavailable.png',
    "available": 'images/iconsets/'+iconTheme+'/available.png',
    "away": 'images/iconsets/'+iconTheme+'/away.png',
    "chat": 'images/iconsets/'+iconTheme+'/chat.png',
    "invisible": 'images/iconsets/'+iconTheme+'/invisible.png',
    "dnd": 'images/iconsets/'+iconTheme+'/dnd.png',
    "xa": 'images/iconsets/'+iconTheme+'/xa.png',
}

// FIXME
function createId() {
    var id = "";
    var aux = "0123456789abcefghijklmnopqrstuvwxyz";
    for (var i=0; i<=3; i++)
        id += aux.charAt(Math.random() * aux.length);
    return id;
}

function htmlEnc(str) {
	try {
		str = str.replace(/&/g,"&amp;");
		str = str.replace(/</g,"&lt;");
		str = str.replace(/>/g,"&gt;");
		str = str.replace(/\"/g,"&quot;");
		str = str.replace(/\n/g,"<br />");
		return str;
	}
	catch (e) { 
        // FIXME
		alert(typeof(str) + ":" + e);
		return null;
	}
}

function incoming(msg) {
	$('#incoming').append("<div>"+msg+"</div><hr />");
    $("#incoming").attr({ scrollTop: $("#incoming").attr("scrollHeight") });
}

function handle_iq(iq) {
	incoming("<strong>Received:</strong> " + iq.xml().htmlEnc());
	con.send(iq.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
}

function handle_message(iq) {
	var html = '<strong>Received Message from '+iq.getFrom()+':</strong><br />';
	var body = htmlEnc(iq.getBody());

	// FIXME
	if (body == '' && iq.getFrom() == 'pubsub.localhost')
		html += htmlEnc(iq.getNode().xml);
	else
		html += htmlEnc(body);

	incoming(html);
}

function handle_presence(iq) {
	var html = '';

	// FIXME
	var userid = iq.getFrom().split("/", 1);
    var rrr = userid.toString().replace("@", "__");

	var presenceImg = $('#presenceImg_' + rrr);
	var presenceStatus = $('#presenceStatus_' + rrr);

	if (!iq.getType() && !iq.getShow()) {
		html += '<strong>'+userid+' has become available.</strong>';
		if (presenceImg) {
            var img = $("<img>").attr({
                'src': status_img['available'],
                'title': 'available',
                'alt': 'available'
            });
            presenceImg.html(img);
		}
	}
	else {
		html += '<strong>' + userid + ' has set his presence to ';

        var type = iq.getType();

		if (type) {
			html += type + '.</strong>';
		
			var img = $("<img>").attr({
			    'src': status_img[type],
			    'title':type,
			    'alt':type
			});
			presenceImg.html(img);
		}
		else {
            var show = iq.getShow();

			html += show + '.</strong>';

			var img = $("<img>").attr({
			    'src': status_img[show],
			    'title':show,
			    'alt':show
			});
			presenceImg.html(img);
		}
	}

	if (iq.getStatus())	{
		var status = htmlEnc(iq.getStatus());
		html += ' ('+status+')';
		presenceStatus.html(status);
	}
	/*else {
		presenceStatus.html(htmlEnc('<change status message>'));
	}*/

    incoming(html);
}

function handle_roster(iq) {
    var list = iq.getQuery().childNodes;
    $('#contatos').html('');

    for (var i=0;i<list.length;i++) {
	    user = list.item(i).getAttribute('jid');

		// FIXME
		var rrr = user.replace('@', "__");

		imgResult = 'jid_image_' + rrr;

		objVcard = new Vcard();
        objVcard.setID('vcard_' + objVcard.createId());
        objVcard.setType('get');
        objVcard.setTo(user);
        objVcard.setFrom(con.fulljid);

		blah = objVcard.getPhotoByJid();

        con.send(blah, _vcard_readByUserReply, imgResult);

        incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());

        var img_user_src = 'images/user_default.png';
        var img_user = $("<img>").attr({
            'src': img_user_src,
            'title': user,
            'alt': user
        });
        var span = $("<span></span>").attr('id', imgResult);
        span.html(img_user);

		var divImgJID = $("<div></div>").attr('class', 'block');
		divImgJID.append(span);

        var href1 = 'javascript:show("'+user+'")';
        var a1 = $("<a></a>").attr('href', href1).text(user);
        var br = $("<br>");
        var id1 = 'presenceImg_' + rrr;
        var spanImg = $("<span></span>").attr('id', id1).text(user);
        var img2 = $("<img>").attr({
            'src': status_img['unavailable'],
            'title':'unavailable',
            'alt':'unavailable'
        });
        spanImg.html(img2);       
        var id2 = 'presenceStatus_' + rrr;
        var spanStatus = $("<span></span>").attr('id', id2);

		var divStatus = $("<div></div>").attr('class', 'block');
		divStatus.append(a1);
		divStatus.append(br);
		divStatus.append(spanImg);
		divStatus.append(spanStatus);

		var id = 'user_' + rrr;
		var div = $("<div></div>").attr('id', id);
		div.append(divImgJID);
        div.append(divStatus);

        $('#contatos').append(div);
	}	
}

function status_list() {
    var ul = $("<ul></ul");
    $.each(
        status_img,
        function (key, value) {
            var img = $("<img>").attr({
                'src': value,
                'title': key,
                'alt': key,
            })
            var li = $("<li></li>");
            li.attr('class', 'status_list');
            li.append(img);
            li.append($("<span></span>").text(key));
            li.click(function () { 
                set_status(key);
            });
            ul.append(li);
        }
    );

	$('#changeMyStatus').html(ul);
	$('#changeMyStatus').show();
}

function set_status(show) {
	var objPresence = new JSJaCPresence();
	objPresence.setTo(con.jid);
	objPresence.setShow(show);
	con.send(objPresence);
	
	$('#changeMyStatus').hide();
}

// FIXME
function cccc(id) {
	var span = $('#'+id);
    var status = $('#test').val();
    if (status == ' ' || status == '') {
        span.html(htmlEnc('<change status message>'));
    }
    else {
        span.html(status);
    }
}

// FIXME
function bbbb(id) {
	var value = $('#user_status_msg').text();
	var span = $('#'+id);
	span.html('<input id="test" value="' + value + '" /> ');

	var button = $("<input>").attr({
	    'type' :'button',
	    'value' : 'Set Status',
    });
    button.click(function () {
            cccc(id);
    })
	span.append(button);
}

function my_status_presence() {
	$('#user_jid').text(con.jid);

    // FIXME
    var rrr = con.jid.replace('@', "__");

	var span_id = 'presenceImg_' + rrr;
	var span = $("<span></span>").attr('id', span_id);
	span.click(function () { 
        status_list();
    });
    var img = $("<img>").attr({
        'src': status_img['available'],
        'title': 'available',
        'alt': 'available'
    });
    span.html(img)
    $('#user_status_img').html(span);

	var span_status_id = 'presenceStatus_' + rrr;
	var span_status = $("<span></span>").attr('id', span_status_id);
	span_status.dblclick(function () { 
        bbbb(span_status_id);
    });
    span_status.html(htmlEnc('<change status message>'));
	$('#user_status_msg').html(span_status);
}

function handle_connected() {
	$('#login_pane').hide();
	$('#box_incoming').show();
	$('#box_contacts').show();
	$('#box_top').show();
	$('#box_me').show();

	my_status_presence();

	var iq = new JSJaCIQ();
	iq.setType('get');
	iq.setID('roster_1');
	query = iq.setQuery('jabber:iq:roster');
	con.send(iq, handle_roster);

	con.send(new JSJaCPresence());
}

function handle_disconnected() {
	$('#login_pane').show();
	$('#box_sendmsg').hide();
    $('#box_incoming').hide();
	$('#box_contacts').hide();
	$('#box_top').hide();
	$('#box_publish_feed').hide();
	$('#box_me').hide();
}

function handle_iq_version(iq) {
	con.send(iq.reply([
		iq.buildNode('name', 'jsjac-xemele'),
		iq.buildNode('version', JSJaC.Version),
		iq.buildNode('os', navigator.userAgent)
		]));
	return true;
}

function handle_iq_time(iq) {
	var now = new Date();
	con.send(iq.reply([
	    iq.buildNode('display', now.toLocaleString()),
		iq.buildNode('utc', now.jabberDate()),
		iq.buildNode('tz', now.toLocaleString().substring(
		        now.toLocaleString().lastIndexOf(' ')+1))
	]));
	return true;
}

function handle_error(e) {
	var e = "An error occured:<br />" + 
		htmlEnc("Code: "+ e.getAttribute('code') +
		"\nType: " + e.getAttribute('type') +
		"\nCondition: " + e.firstChild.nodeName);
		
	showError(e); 
}

function handle_status_changed(status) {
	var html = "<strong>status changed:</strong> " + status;
    incoming(html);
}

function showErrorClose() {
	$('#err').hide();
}

function showError(e) {
	$('#err').show();
	var href = 'javascript:showErrorClose();';
	var a = $("<a></a>").attr('href', href).text("(Close)");
	$('#err').html(e);
	$('#err').append(' ');
    $('#err').append(a);
}

function doLogin(aForm) {
	try	{
		// setup args for contructor
		oArgs = new Object();
		oArgs.timerval = 2000;

        // FIXME
        var type = "binding";
		oArgs.httpbase = HTTP_BIND;

		if (type == 'binding')
			con = new JSJaCHttpBindingConnection(oArgs);
		else
			con = new JSJaCHttpPollingConnection(oArgs);

		setupCon(con);

		// FIXME
		var jid = aForm.jid.value;
		aux = jid.split("@");
		var username = aux[0];
		var domain = aux[1];

		// setup args for connect method
		oArgs = new Object();
		oArgs.username = username;
		oArgs.domain = domain;
		oArgs.resource = 'xemele_' + createId()
		oArgs.pass = aForm.password.value;
		//oArgs.register = aForm.register.checked;
		con.connect(oArgs);
	}
	catch (e) {
		showError(e.toString());
	}
	finally	{
		return false;
	}
}

function setupCon(con) {
	con.registerHandler('message', handle_message);
	con.registerHandler('presence', handle_presence);
	con.registerHandler('iq', handle_iq);
	con.registerHandler('onconnect', handle_connected);
	con.registerHandler('onerror', handle_error);
	con.registerHandler('status_changed', handle_status_changed);
	con.registerHandler('ondisconnect', handle_disconnected);
	con.registerIQGet('query', NS_VERSION, handle_iq_version);
	con.registerIQGet('query', NS_TIME, handle_iq_time);
}

function send_msg(aForm) {
    if (aForm.msg.value == '' || aForm.sendTo.value == '')
        return false;

    if (aForm.sendTo.value.indexOf('@') == -1)
        aForm.sendTo.value += '@' + con.domain;

    var aMsg = new JSJaCMessage();
    aMsg.setTo(aForm.sendTo.value);
    aMsg.setBody(aForm.msg.value);
    con.send(aMsg);

    aForm.msg.value = '';

    return false;
}

function quit()
{
	if (con && con.connected()) {
		con.disconnect();
	}

	$('#login_pane').show();
	$('#box_user_feeds').hide();
	$('#incoming').html('');
    $('#contatos').html('');
}

function init() {
    try { // try to resume a session
        if (JSJaCCookie.read('btype').getValue() == 'binding') {
            con = new JSJaCHttpBindingConnection();
        }
        else {
            con = new JSJaCHttpPollingConnection();
        }

        setupCon(con);

        if (con.resume()) {
	        $('#login_pane').hide();
	        $('#box_incoming').show();
	        $('#box_contacts').show();
	        $('#box_top').show();
	        $('#box_me').show();
        }
    }
    catch (e) {} // reading cookie failed - never mind
}

function show(user) {
	$('#sendTo').val(user); 
	$('#box_sendmsg').show();
	$('#box_publish_feed').hide();
	$('#box_user_feeds').show();

    // FIXME
	var userid = user.split("@", 1);
    var feed = PUBSUB_USERPATH + userid;

    var href1 = 'javascript:subscribeFeed("'+ feed + '")';
	var a1 = $("<a></a>").attr('href', href1).text("Subscribe");

    var href2 = 'javascript:unsubscribeFeed("'+ feed + '")';
	var a2 = $("<a></a>").attr('href', href2).text("Unsubscribe");

	var span = $("<span></span>").text(" ~ ");

    $('#box_feed_menu').html(a1);
    $('#box_feed_menu').append(span);
    $('#box_feed_menu').append(a2);

	var objPubsub = new Pubsub();

    objPubsub.setIQ(objPubsub.pubsubServer,'get','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	var blah = objPubsub.readByUser(user);

    con.send(blah, _readByUserReply, "box_feeds");
	
    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
}

function menu_publish_feed()
{
	$('#box_user_feeds').hide()
	$('#box_sendmsg').hide()
	$('#box_publish_feed').show()
}

function publish_feed(aForm)
{
	var title = aForm.title.value;
	var url = aForm.url.value;
	var service_name = aForm.service_name.value;

    var service_url = service(title, service_name);
    if (service_url) {
        url = service_url; 
    }

	if (title == '' || url == '')
		return false;

	var objPubsub = new Pubsub();
    objPubsub.setIQ(objPubsub.pubsubServer,'set','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	blah = objPubsub.publish(title, url);

    con.send(blah);
	
    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());

	return false;	
}

function showMyFeeds() {
	$('#box_sendmsg').hide();
	$('#box_publish_feed').hide();
	$('#box_user_feeds').show();
	
    // FIXME
    var a = $("<a></a>").attr('href','javascript:;').text("Remove All Feeds");
    var div = $("<div></div>");
	div.append(a);
	$('#box_feed_menu').html(div)
	
	var objPubsub = new Pubsub();

    objPubsub.setIQ(objPubsub.pubsubServer,'get','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	var blah = objPubsub.readByUser(con.fulljid);

    con.send(blah, _readByUserReply, "box_feeds");
	
    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
}

function deleteFeedByID(id) {
	var objPubsub = new Pubsub();
    objPubsub.setIQ(objPubsub.pubsubServer,'set','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	blah = objPubsub.deleteItemById(id);
	
	con.send(blah);

    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
}

function subscribeFeed(feed) {
	var objPubsub = new Pubsub();
    objPubsub.setIQ(objPubsub.pubsubServer,'set','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);
 
    blah = objPubsub.subscribe(feed)
 
    con.send(blah);

    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
}

function unsubscribeFeed(feed) {
	var objPubsub = new Pubsub();
    objPubsub.setIQ(objPubsub.pubsubServer,'set','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	blah = objPubsub.unsubscribe(feed)

    con.send(blah);

    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
}

function service(user, service_name) {
    var url = '';
	switch (service_name) {
		case 'delicious':
			url = "http://del.icio.us/rss/"+user;
			break;
		case 'lastfm':
			url = "http://ws.audioscrobbler.com/1.0/user/"+user+"/recenttracks.rss";
			break;
		case 'flickr':
			url = "http://api.flickr.com/services/feeds/photos_public.gne?id=69644543@N00&lang=en-us&format=rss_200";
			break;
		default:
			url = '';
	}
	return url;
}

function showService(service_name) {
    $('#service_name').val(service_name);

    var title = $('<span></span>').text(service_name);
    // FIXME
    var img = $("<img>").attr({
        'src': 'images/icons/' + service_name + '.png',
        'title': 'available',
        'alt': 'available'
    });
    $('#service').html(img);
    $('#service').append(title);

    if (service_name != 'blog') {
        $('#service_title strong').text('User:');
        $('#service_url').hide();
    }
    else {
        $('#service_title strong').text('Title:');
        $('#service_url').show();
    }
}

function signedFeeds() {
	// FIXME
	//var user = con.username.split("@",1);
	//var node = '/home/localhost/'+user;
	
	alert('erro!');
	
	/*
	var objPubsub = new Pubsub();
    objPubsub.setIQ(objPubsub.pubsubServer,'get','pubsub_'+objPubsub.createId())
    objPubsub.setFrom(con.fulljid);

	blah = objPubSub.getMySubscriptions();
	
    con.send(blah, _getMySubscriptions, "box_right");

    incoming("<strong>Sent:</strong> " + blah.xml().htmlEnc());
    */
}

_readByUserReply =  function(iq, result) {
	var items = iq.getNode().firstChild.firstChild;
    //var node = items.getAttribute('node');

    // clean
    $('#'+result).html('')

	for (var i=0; i<items.childNodes.length; i++) {
		var item = items.childNodes.item(i);
		var title = item.getElementsByTagName('title').item(0);
		var url = item.getElementsByTagName('url').item(0);

    	var div = $("<div></div>").attr('id', 'p_' + i);
        // FIXME
        var remove = 'javascript:deleteFeedByID("'+item.getAttribute('id')+'");';
		var a1 = $("<a></a>").attr('href', remove).text('[x]');
        div.append(a1);
        var aFeed = url.firstChild.nodeValue;
		var a2 = $("<a></a>").attr('href', aFeed).text(title.firstChild.nodeValue);
		div.append(a2);
    	$('#'+result).append(div);

		var pubsub_url = url.firstChild.nodeValue;

		$.getFeed({
			// FIXME 
			url: 'includes/jfeed/proxy.php?url=' + pubsub_url,
			success: function(feed) {
        		var a3 = $("<a></a>").attr('href', feed.link).text(feed.title);
                var h2 = $('<h2></h2>').html(a3)
			    $('#'+result).append(h2);
			    
			    // FIXME
			    for (var i = 0; i < feed.items.length && i < 3; i++) {
				    var item = feed.items[i];
                    var a4 = $("<a></a>").attr('href', item.link).text(item.title);
                    var h3 = $('<h3></h3>').html(a4);
    			    $('#'+result).append(h3);

                    var updated = $("<div></div>").attr('class', 'updated').html(item.updated);
    			    $('#'+result).append(updated);

                    var description = $("<div></div>").html(item.description);
    			    $('#'+result).append(description);
			    }
			}
		});
	}
}

// FIXME
_getMySubscriptions = function(iq, result) {
	alert( iq.getNode().xml );
}

// FIXME
_vcard_readByUserReply = function(iq, result) {
	var node = iq.getNode();
 	var type = node.getElementsByTagName('TYPE').item(0);
	var binval = node.getElementsByTagName('BINVAL').item(0);

	if (type && binval) {
        var src = "data:" + type.firstChild.nodeValue + ";base64," +
            binval.firstChild.nodeValue;
		//?????????????????
		src = src.replace('%0', "\n");
        var img = $("<img>").attr({
            'src': src,
            'title': 'user',
            'alt': 'user',
            'width': '46',
        });

        $('#'+result).html(img);
	}
}
