/**
* Comment Feed Widget
* @requires jquery.js
*/

var riWidget = function() {
	
	var _SITE_PATH = "http://reframeit.com/";
	
	var _JQUERY_PATH = _SITE_PATH + "javascripts/jquery.js";
	var _DATEJS_PATH = _SITE_PATH + "margin/scripts/date.js";
	var _CSS_PATH = _SITE_PATH + "stylesheets/widget.css";
	var $j = null;

	if (typeof(jQuery) == "undefined" || ""+jQuery != "function") document.write('<script type="text/javascript" src="'+_JQUERY_PATH+'"></script>');
	document.write('<script type="text/javascript" src="'+_DATEJS_PATH+'"></script>');
	document.write('<link rel="stylesheet" type="text/css" media="all" href="'+_CSS_PATH+'" />');
	
	// basic hyphenation function to break up words over X characters long
    function hyphenate(str) { 
        var num = 6;
        return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
            return text + "&shy;" + char;
        });
    }
	
	
	return {
		
		settings: {
			targetID: null,
			width: null,
			height: null,
			limit: 4
		},
		
		widget: null,
		
		$target: null,
		
		data: null,

		dataType: null, /* currently either 'user', 'group', or null */
		
		$comments: null,
		
		init: function(json) {
			$j = jQuery.noConflict();
			this.data = json;
			if (typeof(this.data.user) != "undefined")
				this.dataType = "user";
			else if (typeof(this.data.group) != "undefined")
				this.dataType = "group";
			
			// default to document.body if no target is provided
			var target = (this.settings.targetID) ? "#"+this.settings.targetID : document.body;
			var self = this;
			$j(function() {
				self.$target = $j(target).empty();
				self.makeWidget();
			});
		},
		
		/* Load the JSON object */
		makeWidget: function() {
			
			this.createFrame();
			
			this.$comments = $j("ul.ri-comments", this.widget).hide();
			
			// create the user avatar
			this.createAvatar();
			
			
			var that = this;
			if (this.data.comments.length) {
      			// create View ALl Comments link
      			this.createViewAllLink();
    			// loop through and create the comments
      			$j.each(this.data.comments, function(i,comment){	
      				var isLast = (i == that.settings.limit-1) ? true : false;
      				that.createComment(comment, isLast);
      				return !isLast;
      			});
      			this.bindEvents();
			} else {
    			  this.noComments();
			} 
			
  			this.adjustSize();
			this.showComments();
		},
		
		
		/* Creation Methods for constructing HTML	*/
		
		createFrame: function(target) {
			
			var html = '<div id="ri-widget">';
			html += '<div class="ri-wrapper ri-widget-compressed ri-type-' + this.dataType + '">';
			html += '<div class="ri-header">';
			html += '<div class="ri-logo">';
			html += '<a href="'+_SITE_PATH+'">';
			html += '<img src="'+_SITE_PATH+'/images/widget/ri-widget-logo-green.gif"';
			html += ' title="Go to ReframeIt.com" alt="Reframe It" />';
			html += '</a>';
			html += '</div>';
			
      if ( this.dataType == "user" ) {
        
  			html += '<div class="ri-user clearfix">';
  			html += '<span class="ri-thumb"></span>';
  			html += '<span class="ri-username"></span>';
            // html += '<br class="ri-clear" />';
  			html += '</div>';
  			
      }	else if ( this.dataType == "group" ) {
        
  			html += '<div class="ri-group clearfix">';
  			html += '<span class="ri-thumb"></span>';
  			html += '<span class="ri-groupname"></span>';
            // html += '<br class="ri-clear" />';
  			html += '</div>';
  			
      }

            // html += '<br class="ri-clear" />';
			html += '</div>';
			html += '<div class="ri-body clearfix">';
			html += '<ul class="ri-comments clearfix">';
			html += '<li class="loading last">Loading Reframe It Comments...</li>';
			html += '</ul>';
			html += '</div>';
			html += '</div>';
			html += '</div>';
			this.widget = $j(html).appendTo(this.$target);
			// only set the width/height if they were passed in to the settings
			if ( this.settings.width ) this.widget.width( this.settings.width );
			if ( this.settings.height ) $j('ul.ri-comments', this.widget).height( this.settings.height );
			    		
			return this.widget;
		},
		
		createAvatar: function() {
			if (this.dataType == "user")
				this.createUserAvatar();
			else if (this.dataType == "group")
				this.createGroupAvatar();
		},

		createUserAvatar: function() {
			var data = this.data.user;
			var $user = $j('div.ri-user', this.widget);
			var userProfileURL = _SITE_PATH + '/users/' + data.id + '/profile';
			var userThumbnailURL = _SITE_PATH + '/users/' + data.id + '/thumbnail';
			var profileLink = '<a href="' + userProfileURL + '"';
			profileLink += ' title="'+data.display_name+'"></a>';
			var img = '<img src="' + userThumbnailURL + '"';
			img += ' title="'+data.display_name+'" alt="photo" width="28" height="28" />';
			var thumb = $j(img);
			thumb.appendTo($j(".ri-thumb", $user)).wrapAll( profileLink );		
			$j(".ri-username", $user).html(data.display_name).wrapInner( profileLink ).prepend("Comments by:<br />");
			
		},

		createGroupAvatar: function() {
			var data = this.data.group;
			var $group = $j(".ri-group", this.widget);
			var link = '<a href="'+_SITE_PATH+'/groups/'+data.id;
			link += '" title="'+data.display_name+'"></a>';
			var img = '<img src="'+_SITE_PATH+'/groups/'+data.id+'/thumbnail"';
			img += ' title="'+data.display_name+'" alt="photo" width="28" height="28" />';
			var thumb = $j(img);
			thumb.appendTo($j(".ri-thumb", $group)).wrapAll( link );		
			var groupname = data.display_name;
			$j(".ri-groupname", $group).html(groupname).wrapInner( link ).prepend("Group Comments:<br />");
		},
		
		createViewAllLink: function() {
			var html = '<div class="ri-view-all">';
			
			if (this.dataType == "user")
				html += '<a href="' + _SITE_PATH + 'users/' + this.data.user.id + '/comments" target="_blank">';
			else if (this.dataType == "group")
				html += '<a href="' + _SITE_PATH + 'groups/' + this.data.group.id + '/comments" target="_blank">';
				
			html += '<span>View All Comments</span></a>';
			html += '</div>';
			this.$comments.after(html);
		},
		
		createComment: function(data, isLast) {
			if (isLast) {
				var html = '<li class="last clearfix">';
			} else {
				var html = '<li class="clearfix">';
			}

			var has_rating = data.rating ? true : false;
			var rating = has_rating ? data.rating + 3 : 0;
			
			var nd = Date.parse( data.created_at )
            var time = nd.toString( 'h:mmtt' ).replace('PM', 'pm').replace('AM', 'am');
            var date = nd.toString( 'MMM dS' );
            var fullDate = nd.toString( 'MMM dS, yyyy' )
                        
			html += '<span class="ri-rating ri-rating-'+ Math.round(rating) + '"';
			if (has_rating)
				html += ' title="'+rating+'/5 Rating">'+rating+'/5 Rating</span>';
			else
				html += ' title="No Rating">No Rating</span>';
			html += '<div class="ri-meta">';
			if (data.reply_count>0) html += '<a href="' + _SITE_PATH + 'comments/' + data.id + '/replies" target="_blank">';
			html += data.reply_count +' Replies';
			if (data.reply_count>0) html += '</a>';
			html += '<br />';
			html += '<span class="ri-date" title="' + time + " " +  fullDate + '">' + time + " " +  date + '</span>';
			html += '</div>';
			
			html += '<div class="ri-reference">';
    		html += '<div>';
    		html += '<p>';
			html += 'Page: <a href="'+data.reference_points[0].uri+'" target="_blank">';
            html += data.reference_points[0].title+'</a>';
    		html += '</p></div>';
    		html += '</div>';
			
			
			var ref = data.reference_points[0].references[0];
			/** text/img reference */
			if (ref.type == "text" || ref.type == "image") {
      	        html += '<div class="comment-reference">';
      	        html += '<h4><a href="#"><span>' + ref.type + ' Reference</span></a></h4>';
      	        html += '<div class="content"><div class="padding">';
    			if (ref.type == "image") {
      			    html += '<div class="image">';
      			    html += '<img src="' + ref.text + '" width="300" title="Reframe It is not responsible for the contents of this image"';
      			    html += ' alt="Referenced Image" />';
      			    html += '</div>';
    			} else {
    			    html += '<span class="quote-l">&nbsp;</span>';
    			    html += hyphenate(ref.text);
    			    html += '<span class="quote-r">&nbsp;</span>';
  			    }
    		html += '</div></div>';
    	  html += '</div>';
    	}
    	
    	
    	
			html += '<div class="ri-comment">';
			/** Speech Bubble */
			html += '<div class="speech-bubble click-me hover-me' + ((ref.type == "text" || ref.type == "image") ? ' has-reference' : '') + '">';
			html += '<div class="content closed-bubble"><div class="padding">';
			html += hyphenate(data.text);
        	html += '<div class="view-comment">';
        	html += '<a href="' + _SITE_PATH + 'comments/' + data.id + '" rel="bookmark" target="_blank">';
        	html += 'View Comment &rarr;</a></div>';
        	html += '</div></div>'; 
        	if (this.dataType == "group"){
        	    html += '<span class="arrow arrow-bl"></span>';
    	    }
            html += '<div class="bottom-cap"><span></span></div>';
      		html += '</div>';
    		html += '</div>'; // /ri-comment
			
			if (this.dataType == "group") {
			    
                html += '<div class="details">';
                html += '<span class="thumbnail"><a href="'+_SITE_PATH + 'users/'+data.user.id+'/profile">';
                var userThumbnailURL = _SITE_PATH + '/users/' + data.user.id + '/thumbnail';
                html += '<img src="' + userThumbnailURL + '" alt="photo" height="28" width="28">';
                html += '</a></span>';
                html += '<p><a href="'+_SITE_PATH + 'users/'+data.user.id+'/profile">'+data.user.display_name+'</a>';
                html += '<span class="view-all-users-comments"><a href="'+_SITE_PATH + 'users/'+data.user.id+'/comments" title="View all comments from '+data.user.display_name+'">View all Comments</a></span>';
                html += '</p>';
                html += '</div>';                
			}
			
			html += '</li>';

			/** Append Comment to the list */
			$j(html).appendTo(this.$comments);
		},
		
		/* when the width of the widget is adjusted, different css rules are applied/removed to accomodate */
		adjustSize: function() {
		    // Header -- if it's wide enough, float the user/group avatar to the right
            var headerW = $j('div.ri-'+this.dataType+' .ri-'+this.dataType+'name', this.widget).width();
            headerW += $j('div.ri-'+this.dataType+' .ri-thumb', this.widget).width();
            headerW += $j('div.ri-logo', this.widget).width();
            headerW += 30; // allow for padding;
            if (headerW < this.widget.width()) {
                $j('.ri-wrapper', this.widget).removeClass('ri-widget-compressed');
            } else {
                $j('.ri-wrapper', this.widget).addClass('ri-widget-compressed');
            }
		},
			    
		bindEvents: function() {
		    
		    /** User/Group avatars */
		    $j("div.ri-user, div.ri-group", this.widget).click(function() {
                location.href = $j('a', this)[0];
                return false;
			}).hover(function() {
			    $j(this).addClass('ri-avatar-hover');
			}, function() {
			    $j(this).removeClass('ri-avatar-hover');
			});
			
		    /** Page Reference hover event */
		    $j('div.ri-reference div', this.$comments).hover(function() {
                $j(this).addClass('hover');
            }, function() {
                $j(this).removeClass('hover');
            }).click(function() {
                location.href = $j('a', this)[0];
                return false;
            });
            
            /** Speech Bubble hover events and click event takes you to comment */
            $j('div.speech-bubble', this.$comments).hover(function() {
                $j(this).addClass('hover');
            }, function() {
                $j(this).removeClass('hover');
            }).click(function() {
                // location.href = $j('.view-comment a', $j(this)).attr('href');
                window.open( $j('.view-comment a', $j(this)).attr('href'), '_blank' );
                return false;
            });        	

        	/** Comment 'Text Reference' collaposable block */
        	$j('div.comment-reference h4 a', this.$comments).click(function() {
        		$j(this).toggleClass('open');
        		$j(this).parent().siblings('.content').toggle();
        		return false;
        	});
		},
		
		noComments: function() {
			var html = '<li class="no-comments">There are currently no comments to display...</li>';
			// append comment to the list and bind click/hover events
			$j(html).appendTo(this.$comments);
		},
		
		showComments: function() {
			// remove loading li and animate the list in
			$j(".loading", this.$comments).remove();
			this.$comments.fadeIn();
		}
		
	};
	
}();