//Display a pubsub item
Peeq.ItemView.prototype = {
    
    resetSearch: function(empty_results) {
	//ignore current items until new subscription is successful.
	app.subscribing = true;

	var search_term = $("#search-area").attr("value");
	var timestamp = $("#clock").text();
	if(empty_results == null)
	{
	    empty_results = true;
	}
	if(app.connected)
	{

	    var searched_html = $("#search_result").clone();
	    searched_html.find('#content').html("Search started. Waiting for results...<br/><br/><br/>");
	    searched_html.removeAttr("id");
	    searched_html.find('.favicon').hide();
	    searched_html.find('.time-stamp').text(timestamp);
	    searched_html.show();
	    $("#container-header h4").text("results in real time!");
	    $("#container-footer").show();
	    if(empty_results || this.count == 0)
	    {
		this.count = 0;
		$("#published_items").empty();
		$("#clock_since").text(timestamp);
		$("#container-footer p").text("0 new results");
		$("#couter").text("0 mentions ");
		$("#published_items").prepend($(searched_html.get(0)).fadeIn());
	    }

	    
	}
	else
	{
	    clientview.reconnectView.reconnectWithTimer();
	}
    },
    showCount: function() {
	if (this.count == 1)     
	{ 
	    $("#container-footer p").text(this.count + " new result");
	    $("#counter").text(this.count + " mention "); 
	}
	else 
	{ 
	    $("#container-footer p").text(this.count + " new results");
	    $("#counter").text(this.count + " mentions "); 
	}
    },
    findSource: function(tag) {
	//jaiku source
	var sources = ["jaiku",
		       "twitter",
		       "identica",
		       "flickr",
		       "livejournal",
		       "wordpress",
		       "friendfeed",
		       "youtube",
		       "xmpp-muc",
		       "seesmic"];

	var retval = "default";
	jQuery.each(sources, function(i, val) {
	    var clean_tag = tag.replace(/\./g,"");

	    if(clean_tag.match(RegExp(val,'g')))
	    {
		retval = val;
	    }
	});

	return retval;
    },
    urlwbr: function(str, num) {
	//Add word breaks to words (spaces , followed by word characters)
	return str.replace(RegExp("(\\S{" + num + "})(\\S)", "g"), 
			   function(all,text,char){
			       return text + "<wbr />" + char;
			   });
    },
    htmlLink: function(text) {
	var linksReg = /((?:ht|f)tps?:\/\/[\S|\?]+)/g;
        var ahtmlReg = /\w+=.*(?:ht|f)tps?:\/\//g;
        var retval = "";
        var text_words = text.split(' ');
	var my_self = this;
        jQuery.each(text_words, function(i,text_val) {
	    var amatch = text_val.match(ahtmlReg);
            var match = text_val.match(linksReg);
            if (match && !amatch)
            {
                var urltext = text_val;
                jQuery.each(match,function(i,val) {
		    
                    var atext = my_self.urlwbr(match[i],20);
		    
                    var newEl = ["<a href=\"",
                                 match[i],
                                 "\" target=\"_blank\">",
                                 atext,
                                 "</a> "];
                    //escape special regular expression characters
                    var url_regex = match[i].replace(/(\?|\+|\-|\||\^|\$|\(|\)|\*)/g,'\\$1');
		    
                    
                    urltext = urltext.replace(new RegExp(url_regex,"g"), 
                                              newEl.join(""));
		    
                });
                retval += urltext + " ";
            }
	    else
	    {
		retval += text_val + " ";
	    }

	});
	//remove trailing whitespace
	retval = jQuery.trim(retval);
	return retval;
    },

    scaleImage: function(elem) {
	var selector = 'img';
	var retval = false;
	var item_view = this;
	var img_elm = elem.find(selector);
	if(img_elm.length != 0)
	{
	    retval = true;
	}
	img_elm.hide();

	img_elm.load( function() {
	
	    //Sets the max width, in pixels, for every image based on
	    //the publish div size.
	    var max_width = $('#published_items').width() - 10;
	    var max_height = $('#published_items').height() - 10;
	    
	    if(Peeq.MAX_IMAGE_WIDTH != null)
	    {
		max_width = Peeq.MAX_IMAGE_WIDTH;
	    }
	    if(Peeq.MAX_IMAGE_HEIGHT != null)
	    {
		max_height = Peeq.MAX_IMAGE_HEIGHT;
	    }
	    jQuery(this).each(function(){

		var width = jQuery(this).width();
		if(width == 0)
		{
		    width = jQuery(this).attr('width');
		}
		var height = jQuery(this).height();
		if(height == 0)
		{
		    height = jQuery(this).attr('height');
		}
		var ratio = (height / width );		
		var new_width = width;
		var new_height = height;
		if (width > max_width) {
		   	    
		    new_width = max_width;
		    new_height = (new_width * ratio);		
		    
		}
		if(new_height > max_height)
		{
		    ratio = (new_height/new_width);
		    var new_height = max_height;
		    new_width = (new_height * ratio);		    
		}
		//jQuery(this).height(new_height).width(new_width);
		
	    });
	    jQuery(this).show();
	    elem.fadeIn();
	    item_view.count += 1;
	});
	return retval;
    },
    
    displayItem: function(stanza) {

	var items = $(stanza).find("item");

	var item_view = this;
	items.each( function(i, it) {

	    var item = $(it).find("entry");
	    var author = item.find("author").find("name");
	    var content_url = item.find("link").attr("href");
	    var content = item.find("content");
	    var summary = item.find("summary");
	    var title = item.children("title").text();
	    var avatar = item.find("icon").text();
	    var tag = item.find("id").text();
	    var read_more_link = "";
	    var read_more_start = "<br/><a class='read_more_link' target='_blank' href='";
	    var read_more_text = "'>Read More>></a>";
	    var item_source = item_view.findSource(tag);

	    if(item_source == "identica")
	    {
		if(avatar.match(/default/g))
		{
		    avatar = "images/avatar.png";
		}
	    }
	    if(!title)
	    {
		title = "< no title >";
	    }
	    if(!content_url)
	    {
		content_url = item.find("source").text();
	    }
	    var avatar_html = "";
	    if(!avatar)
	    {
		avatar = "images/avatar.png";
	    }
	    else
	    {
		avatar_html = "<img src=\""+avatar+"\" />";
	    }
	    
	    var timestamp = $("#clock").text();

	    var content_text = content.text();
	    //parse data into jquery object so you can find html elements
	    var content_html = $("<div>"+content_text+"</div>");
	    content_html.find('script').remove();
	    //empty style attributes
	    content_html.find('[style]').attr('style','');
	    //replace links with target _blank
	    content_html.find('a').attr('target','_blank');
	    
	    content_text = content_html.html();


	    content_text = item_view.htmlLink(content_text);

	    
	    if(content_html.text().length > Peeq.MAX_ITEM_SIZE)
	    {
		//take a substring of content_text
		content_text = content_text.substring(0,Peeq.MAX_ITEM_SIZE);
		read_more_link = read_more_start + content_url+read_more_text;
	    }
	    if(summary.length > 0)
	    {
		read_more_link = read_more_start + content_url+read_more_text;
		content = summary;
	    }
	    var published_item_html = $("#search_result").clone();
	    published_item_html.removeAttr("id");
	    published_item_html.addClass(item_source);
	    published_item_html.find('.source_id').text(item_source);
	    published_item_html.find('.time-stamp').text(timestamp);
	    published_item_html.find('#content_url').attr('href',content_url);
	    published_item_html.find('#content_title').attr('href',content_url);
	    published_item_html.find('#content_title').text(title);
	    published_item_html.find('#content').html(avatar_html+content_text+read_more_link);
	    published_item_html.find('#author').text(author.text());


	    //scale images to fit display
	    if(!item_view.scaleImage(published_item_html))
	    {
		//if an image was not found to be scaled show the element
		published_item_html.show();
		//bump the count
		item_view.count += 1;
		//only show flash after it has been loaded
		var obj_elem = published_item_html.find('object');
		if (obj_elem.length > 0)
		{
		    obj_elem.hide();
		    published_item_html.hide();
		    obj_elem.load(function() {
			obj_elem.show();
			published_item_html.show();
		    });
		    $("#published_items").prepend($(published_item_html.get(0)));
		}
		else
		{
		    $("#published_items").prepend($(published_item_html.get(0)).fadeIn());
		}
	    }
	    else
	    {
		published_item_html.hide();
		$("#published_items").prepend($(published_item_html.get(0)));
	    }
	    
	    item_view.showCount();
	    var itemview_divs = $("#published_items > div");
	    var itemviewlist = $("#published_items");
	    if(itemview_divs.length > Peeq.MAX_SCROLL_SIZE)
	    {
		var msg_index = itemview_divs.length - 1;
		var lastelem = itemview_divs.get(msg_index);
		
		$(lastelem).remove();
	    }
	});
    }
};
