(function($) {
    
    var photos;
     
    $.fn.photos = function() 
    {
        photos = $('.photos');
        this.displayPhoto = displayPhoto;
        if ($('.avatar').attr('alt') == cuname) {
            var d = $('<p>✗ Delete</p>').css({'text-align': 'center', 'cursor': 'pointer'});
            $('.photos td a').parent().append(d);
            $('.photos td p').click(function() {
                if (confirm("Are you sure you want to delete this photo?")) {
                    var td = $(this).parent();
                    var pk = td.find('a').attr('href').substr(1)
                    $.post('delete/', {'pk': pk}, function(r) {
                        td.animate({opacity:0}, 500, function() {
                            td.remove()
                        })
                    });
                }
            })
        }
        return this;
    };
    
    displayPhoto = function(a)
    {

        $('#photo').css('display', 'block');
        
        photos.find('.selected').removeClass('selected');
        a.addClass('selected');

        $('#photo .source').html($('<img>').attr('src', a.attr('alt')));
        
        // photo what of what?
        photo_n = 1;
        photos.find('a').each(function(i) {
            if (a.attr('href') == $(this).attr('href')) {
                photo_n = i + 1;
                return true;
            }
        });
        $('#photo .l').eq(0).html('<b>Photo</b> ' + photo_n + ' of ' + photos.find('a').length)
        
        $('#photo .source').append('<div style="text-align:left;padding:0 10px;"><b>Uploaded: </b>' + a.find('img').attr('alt') + '</div>')
        
        
        updatePagination();
        
    };
    
    updatePagination = function()
    {
        
        
        var p = photos.find('a');
        
        
        p.each(function(i) {
            
            if ($(this).hasClass('selected')) {
                var href = p.eq(i+=1).attr('href');
                if (href == undefined) {
                    href = photos.find('a:first').attr('href');
                }
                 $('.next').attr('href', href);
                
                var href = p.eq(i-=2).attr('href');
                if (href == undefined) {
                    href = photos.find('a:last').attr('href');
                }
                $('.prev').attr('href', href);
                return false;
            }
            
        });
    };
    

})(jQuery);











(function($) {




    $.fn.initTimeLine = function() {

        var nodes = eval(this.find('.data').val());
        this.find('#nodes').html(render(nodes));
        
        $('.add-node').find('textarea').val('').attr('disabled', '');
        $('.add-node').find('button').val('Share').attr('disabled', '').click(function() {
                
            var t = $('.add-node textarea');
            var b = $(this);
            if (t.val().length == 0) return;
            t.attr('disabled', 'disabled');
            b.attr('disabled', 'disabled').text('Sharing...');
            
            $.post('add-event-node/', {'text': t.val()}, function(r) {
                var li = renderEventNode(r.pk, r.kind, r.uname, r.upic, r.fname, r.ts, r.data).css('opacity', 0);
                $('#timeline ul').eq(0).prepend(li);
                li.animate({'opacity': 1}, 500);
                t.attr('disabled', '').val('');
                b.attr('disabled', '').text('Share');
            });
        });
    };
    
	render = function(nodes) {
	    
		var ul = $('<ul>');
		$(nodes).each(function() {
            parent_pk = this.pk;
            var li = renderEventNode(parent_pk, this.kind, this.uname, this.upic, this.fname, this.ts, this.data);
		    ul.append(li);
			
			if (this.children) {
			    var child_ul = $('<ul>');
			    $(this.children).each(function() {
			        child_ul.prepend(renderEventNode(this.pk, this.kind, this.uname, this.upic, this.fname, this.ts, this.data, parent_pk));
			    });
			    li.append(child_ul);
			    // all children have a comment box
                child_ul.append(renderEventNode(this.pk, 'subcomment', cuname, '', cfname, null, null, parent_pk))
			}
		});
		return ul;
	};
	
	renderEventNode = function(pk, kind, uname, upic, fname, ts, data, parent_pk)
	{
	    if (data) {
	        data = eval(data);
	        if (data.length == 1 && kind == 'img') {
	            data = [data[0],]
	        } else if (data.length == 1) {
	            data = data[0];
	        }
    	}

		if (ts) {
            ts = ts.split('.')[0];
		}


		// All rows are essentially the same.
        
		
 		var li = $('<li>').attr('id', 'node-' + pk).addClass(kind);
        if (kind != 'subcomment') {
            var src = '/media/heat_coza/social/profile/' + upic + '_120.jpg';   
 		    li.append($('<img>').attr({
 		            'src': src,
					'alt': uname,
					'class': 'avatar'
				}));
 		}
        li.append($('<div>').addClass('body'));
			
		// Determine how to display the database based on the kind.
		switch (kind) {
		    case 'stx': // plaint text
		        li.find('.body').append(
		            $('<p>').html(userProfileLink(uname, fname) + ' ' + data.text), 
		            $('<span>').append($('<abbr title="' + ts + '">' + ts + '</abbr>').timeago())
		        );
		        break;
		    
		    
		    case 'sgx':
		        li.find('.body').append(
		            $('<p>').html(userProfileLink(uname, fname) + ' has uploaded new photos.'), 
		            $('<span>').append($('<abbr title="' + ts + '">' + ts + '</abbr>').timeago())
		        );
		        
		        var photos = $('<div class="photos"></div>');

                $(data).each(function(i) {
                    photos.append($('<a href="/social/profile/' + uname + '/photos/#' + this.pk + '"><img src="' + this.src + '"></a>'));
                });
                
                li.find('.body p').append(photos)
		        
		        break;
		    
		    
		    case 'subcomment': // sub comment
		    
		        if (cuname == '') return false;
		        
		        li.find('.avatar').remove();
                li.find('.body').append('<p>Write a comment</p><textarea id="textarea-' + parent_pk + '" name="textarea-' + parent_pk + '"></textarea><button>Comment</button>');
                li.find('textarea').elastic();
                li.find('.body button').click(function() {
                    
                    var parent_pk = $(this).parent().parent().attr('id').split('-')[1];
                    var b = $(this);
                    var t = b.parent().find('textarea');
                    if (t.val().length == 0) return false;
                    
                    t.attr('disabled', 'disabled');
                    b.attr('disabled', 'disabled').text('Saving...');
                    
                    $.post('/social/profile/' + uname + '/add-event-node/', {'text': t.val(), 'parent_pk': parent_pk}, function(r) {
                        var li = renderEventNode(r.pk, r.kind, r.uname, r.upic, r.fname, r.ts, r.data).css('opacity', 0);
                        
                        t.parent().parent().before(li);
                        li.animate({'opacity': 1}, 500);
                        b.attr('disabled', '').text('Comment');
                        t.attr('disabled', '').val('');
                        
                    });
                });
		        break;
		}
		
		if (parent_pk == null && cuname != '') {
            var span = li.find('span').append(
                ' &middot; ',
                $('<a>').attr('href', '#comment').text('Comment')
                    .click(function() {
	                    // add a child not

	                    var parent_ul = $(this).parent().parent().parent();
	                    
	                    // check to see if we already have a child node.
                        if (parent_ul.find('textarea').length > 0) {
                            parent_ul.find('textarea').focus();
                            return false;
                        }
                        
                        // otherwise you've got to build one.
                        
                        var child_ul = $('<ul>');
                        child_ul.append(renderEventNode(pk, 'subcomment', cuname, cfname, null, null, null))
                        parent_ul.append(child_ul);
                        child_ul.find('textarea').focus();
	             
	                    return false;
	                })
                );
	        
        }
        
        
        // events
        
        li.mouseenter(function() {

            e = false;
            if (li.find('img').attr('alt') == cuname || $('.avatar').attr('alt') == cuname) {
                e = true;
            }
            
            if ($(this).hasClass('subcomment')) {
                e = false;
            }
            
            if (!e) {
                return;
            }
            
            var rm = $('<div class="rm">Delete?</div>').click(function() {
                
                var pk = li.attr('id').replace('node-', '');2
                if (confirm("Are you sure you want to delete this post?")) {
                    $.post('/social/profile/' + uname + '/delete-event-node/', {'pk': pk}, function(r) {
                        
                        if (r == 1) {
                            li.animate({opacity:0}, 500, function() { $(this).remove(); });
                        }
                    });
                }
            });
            $(this).append(rm);
            
            
            
        }).mouseleave(function() {
            $(this).find('.rm').remove();
        });
        
        
			
		return li;
	};
	
	userProfileLink = function(uname, fname)
	{
		return '<a href="/social/profile/' + uname + '/" class="uname">' + (fname.length > 0 ? fname : uname) + '</a>';
	};
	
	
	safe = function(t)
	{
        return t.replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/\"/g, "&quot;")
        .replace(/'/g, "&#39;")
        .replace(/\n/g, '<br>');
	};

 
})(jQuery);

/* timeago, elastic textarea */
(function($){$.timeago=function(timestamp){if(timestamp instanceof Date)return inWords(timestamp);else if(typeof timestamp=="string")return inWords($.timeago.parse(timestamp));else return inWords($.timeago.datetime(timestamp));};var $t=$.timeago;$.extend($.timeago,{settings:{refreshMillis:60000,allowFuture:false,strings:{prefixAgo:null,prefixFromNow:null,suffixAgo:"ago",suffixFromNow:"from now",ago:null,fromNow:null,seconds:"less than a minute",minute:"about a minute",minutes:"%d minutes",hour:"about an hour",hours:"about %d hours",day:"a day",days:"%d days",month:"about a month",months:"%d months",year:"about a year",years:"%d years"}},inWords:function(distanceMillis){var $l=this.settings.strings;var prefix=$l.prefixAgo;var suffix=$l.suffixAgo||$l.ago;if(this.settings.allowFuture){if(distanceMillis<0){prefix=$l.prefixFromNow;suffix=$l.suffixFromNow||$l.fromNow;}distanceMillis=Math.abs(distanceMillis);}var seconds=distanceMillis/1000;var minutes=seconds/60;var hours=minutes/60;var days=hours/24;var years=days/365;var words=seconds<45&&substitute($l.seconds,Math.round(seconds))||seconds<90&&substitute($l.minute,1)||minutes<45&&substitute($l.minutes,Math.round(minutes))||minutes<90&&substitute($l.hour,1)||hours<24&&substitute($l.hours,Math.round(hours))||hours<48&&substitute($l.day,1)||days<30&&substitute($l.days,Math.floor(days))||days<60&&substitute($l.month,1)||days<365&&substitute($l.months,Math.floor(days/30))||years<2&&substitute($l.year,1)||substitute($l.years,Math.floor(years));return $.trim([prefix,words,suffix].join(" "));},parse:function(iso8601){var s=$.trim(iso8601);s=s.replace(/-/,"/").replace(/-/,"/");s=s.replace(/T/," ").replace(/Z/," UTC");s=s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2");return new Date(s);},datetime:function(elem){var isTime=$(elem).get(0).tagName.toLowerCase()=="time";var iso8601=isTime?$(elem).attr("datetime"):$(elem).attr("title");return $t.parse(iso8601);}});$.fn.timeago=function(){var self=this;self.each(refresh);var $s=$t.settings;if($s.refreshMillis>0){setInterval(function(){self.each(refresh);},$s.refreshMillis);}return self;};function refresh(){var data=prepareData(this);if(!isNaN(data.datetime)){$(this).text(inWords(data.datetime));}return this;}function prepareData(element){element=$(element);if(!element.data("timeago")){element.data("timeago",{datetime:$t.datetime(element)});var text=$.trim(element.text());if(text.length>0)element.attr("title",text);}return element.data("timeago");}function inWords(date){return $t.inWords(distance(date));}function distance(date){return(new Date().getTime()-date.getTime());}function substitute(stringOrFunction,value){var string=$.isFunction(stringOrFunction)?stringOrFunction(value):stringOrFunction;return string.replace(/%d/i,value);}document.createElement("abbr");document.createElement("time");})(jQuery);
;(function(jQuery){jQuery.fn.extend({elastic:function(){var mimics=['paddingTop','paddingRight','paddingBottom','paddingLeft','fontSize','lineHeight','fontFamily','width','fontWeight'];return this.each(function(){if(this.type!='textarea'){return false;}var $textarea=jQuery(this),$twin=jQuery('<div />').css({'position':'absolute','display':'none'}),lineHeight=parseInt($textarea.css('line-height'),10)||parseInt($textarea.css('font-size'),'10'),minheight=parseInt($textarea.css('height'),10)||lineHeight*3,maxheight=parseInt($textarea.css('max-height'),10)||Number.MAX_VALUE,goalheight=0,i=0;$twin.appendTo($textarea.parent());var i=mimics.length;while(i--){$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));}function setHeightAndOverflow(height,overflow){curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow});}}function update(){var textareaContent=$textarea.val().replace(/<|>/g,' ').replace(/\n/g,'<br />').replace(/&/g,"&amp;");var twinContent=$twin.html();if(textareaContent+'&nbsp;'!=twinContent){$twin.html(textareaContent+'&nbsp;');if(Math.abs($twin.height()+lineHeight-$textarea.height())>3){var goalheight=$twin.height()+lineHeight;if(goalheight>=maxheight){setHeightAndOverflow(maxheight,'auto');}else if(goalheight<=minheight){setHeightAndOverflow(minheight,'hidden');}else{setHeightAndOverflow(goalheight,'hidden');}}}}$textarea.css({'overflow':'hidden'});$textarea.keyup(function(){update();});$textarea.live('input paste',function(e){setTimeout(update,250);});update();});}});})(jQuery);
