/*

  Copyright Stanziq, Inc. 2008

*/
var clientview = null;
var app = null;
var Peeq = {

    BOSH_URL: "/xmpp-httpbind",
    PREBIND_URL: "/http-pre-bind",
    XMPP_DOMAIN: "collecta.com",
    //XMPP_DOMAIN: "localhost",
    DEFAULT_WAIT: 60,
    DEFAULT_HOLD: 1,
    DEFAULT_ROUTE: "xmpp:xmpp.collecta.com:5222",
    //DEFAULT_ROUTE: "xmpp:127.0.0.1:5222",
    DEFAULT_WINDOW: 5,
    PUBSUB_COMPONENT: 'pubsub.collecta.com',
    SEARCH_COMPONENT: 'search.collecta.com',
    ARCHIVE_COMPONENT: 'search.collecta.com',
    MAX_SCROLL_SIZE: 500,
    MAX_ITEM_SIZE: 2000,
    NS: {
	SEARCH: 'jabber:iq:search',
	PUBSUB:"http://jabber.org/protocol/pubsub",
	PUBSUB_SUBSCRIBE_OPTIONS:"http://jabber.org/protocol/pubsub#subscribe_options",
	ARCHIVE_OPTIONS:"collecta#options",
	DSL_OPTIONS:"collecta#query",
	RESULTS_OPTIONS:"collecta#notify"
    },
    start_sub: false,
    Application: function() {
	//try prebind url first
	this.connection = new Strophe.Connection(Peeq.PREBIND_URL);
	this.connected = false;
	this._disconnected = false;
	this.subscribing = false;
    },

    PubSub: function() {
    },
    Archive: function() {
    },
    ClientView: function() {
	this.itemView = new Peeq.ItemView();
	this.reconnectView = new Peeq.ReconnectView();
    },
    ItemView: function() {
	this.count = 0;
    },
    ReconnectView: function() {
        this.timeout_time = 5;
	this.saved_timeout = 5;
	this.display = true;
    },
    unload: function() {
	jQuery(document).trigger('peeq_exit',[]);
	
	var ps0 = new Peeq.PubSub();
	ps0.unsubscribe(app.connection.jid,
			Peeq.SEARCH_COMPONENT,
			"search",
	function() {
	    app.disconnect();
	}
			);		
    },
    defaultInit: function() {
	clientview = new Peeq.ClientView();
	clientview.init();
    },
    init: function(init_function) {
	$(document).ready(function(){
	    if(!app)
	    {
		app = new Peeq.Application();
	    }
	    app.run();

	    init_function();
	    
	    $(document).unload(function(){
                if(app)
                    {
                        Peeq.unload();
                    }
            });

            window.onbeforeunload = function(){
                if(app)
                {
                    Peeq.unload();
                }
            };
            
            $(window).unload(function(){
                if(app)
                {
		    Peeq.unload();
		}
            });

	});
    },
    searchUnSubscribe: function() {
	app.subscribing = true;
	var ps = new Peeq.PubSub();
	var iqid = ps.unsubscribe(app.connection.jid,
				  Peeq.SEARCH_COMPONENT,
				  "search",
	    function(stanza) {
		var error = $(stanza).find("error");
		
		if(error.length != 0)
		{
		    console.error("Error unsubscribing from node.");
		}
		else
		{
		    jQuery(document).trigger('peeq_unsubscribed',[]);
		}
	    });
    },
    _searchSubscribe: function(keywords,updates,cb) {
	var retval = {};

	var keyword_elem = Strophe.xmlElement("field",
					      [["var",
						Peeq.NS.DSL_OPTIONS],
					       ["type",
						'text-single'],
					       ["label",
						"keyword to match"]]);
	
	var search_options = [];
	var value = Strophe.xmlElement("value",[]);
	
	if (keywords)
	{
	    var text = Strophe.xmlTextNode(keywords);
	    value.appendChild(text);
	    keyword_elem.appendChild(value);
	    search_options.push(keyword_elem);
	}
	
	if (updates)
	{
	    var notify_elem = Strophe.xmlElement("field",
						 [["var",
						   Peeq.NS.RESULTS_OPTIONS],
						  ["type",
						   'text-multi'],
						  ["label",
						   "keyword to notify"]]);
	    jQuery.each(updates,function(i,val) {
		var value = Strophe.xmlElement("value",[]);
		
		
		var text = Strophe.xmlTextNode(val);
		value.appendChild(text);
		notify_elem.appendChild(value);
		search_options.push(notify_elem);
	    });
	}
	//ask for archived items
	var ars = new Peeq.Archive();
	var aid = ars.search(app.connection.jid,
			     Peeq.ARCHIVE_COMPONENT,
			     [keywords],
			     function(data){
				 if($(data).find("error").length > 0)
				 {
				     console.error("error requesting archive.");
				     console.log(data);
				 }
				 else
				 {
				     //display each new item.
				     jQuery(document).trigger('peeq_new_message',[data]);
				 }
			     });
	retval["archiveid"] = aid;
	var ps = new Peeq.PubSub();
	
	var iqid = ps.subscribe(app.connection.jid,
				Peeq.SEARCH_COMPONENT,
				"search",
				search_options,
		         function(stanza) {
			   
			     var error = $(stanza).find("error");

			     if(error.length != 0)
			     {
				 console.error("Error subscribing to node.");
				 jQuery(document).trigger('peeq_error',["Error subscribing to node."]);
			     }
			     else
			     {
				 app.subscribing = false;
				 jQuery(document).trigger('peeq_subscribed',
							  []);
			     }
			     
			 });
	retval["searchid"] = iqid;
	if(cb)
	{
	    cb(retval);
	}
    
    },  
    /* Function Peeq.searchSubscribe 
     *   Used to subscribe to the xmpp search interface.
     * Parameters
     *   (String) keywords - the search string 
     *   (Array) updates - the arrah of search strings to only get update counts on.
     *
     * See http://trac.stanziq.com/wiki/SearchApi#SavedSearchesandSearchupdatenotifications. for more information.
    */
    searchSubscribe: function(keywords,updates,cb) {
	var retval = {};
	//ensure we are not subscribed
	var ps0 = new Peeq.PubSub();
	ps0.unsubscribe(app.connection.jid,
			Peeq.SEARCH_COMPONENT,
			"search",
			function() {
	    Peeq._searchSubscribe(keywords,updates,cb);
	});
	return retval;
    },
    searchWoUnSubscribe: function(keywords,updates,cb) {
	Peeq._searchSubscribe(keywords,updates,cb);
    }
};
