(function(){RB.AbstractCommentBlock=Backbone.Model.extend({defaults:{hasDraft:false,canDelete:false,draftComment:null,serializedComments:[],count:0},initialize:function(){var comments=this.get('serializedComments'),newSerializedComments=[];if(comments.length>0){_.each(comments,function(comment){comment.text=$("<div/>").html(comment.text).text();if(comment.localdraft){this.ensureDraftComment(comment.comment_id,comment.text);}else{newSerializedComments.push(comment);}},this);this.set('serializedComments',newSerializedComments);}else{this.ensureDraftComment();}
this.on('change:draftComment',this._updateCount,this);this._updateCount();},isEmpty:function(){return this.get('serializedComments').length===0&&!this.has('draftComment');},createComment:function(id){console.assert(false,'This must be implemented by a subclass');},ensureDraftComment:function(id,text){var self=this,comment;if(this.has('draftComment')){return;}
comment=this.createComment(id);if(text){comment.text=text;}
$.event.add(comment,'destroyed',function(){self.set('draftComment',null);self._updateCount();});$.event.add(comment,'saved',_.bind(this._updateCount,this));this.set('draftComment',comment);},_updateCount:function(){var count=this.get('serializedComments').length;if(this.has('draftComment')){count++;}
this.set('count',count);}});RB.AbstractReviewable=Backbone.Model.extend({defaults:{serializedComments:[]},commentBlockModel:null,reviewableIDField:null,initialize:function(){console.assert(this.commentBlockModel,'commentBlockModel must be defined');this.commentBlocks=new Backbone.Collection();this.commentBlocks.model=this.commentBlockModel;_.each(this.get('serializedComments'),this.addCommentBlocks,this);},addCommentBlocks:function(serializedComment){console.assert(false,'This must be implemented by a subclass');}});RB.CommentIssueManager=Backbone.Model.extend({defaults:{reviewRequest:null},initialize:function(){this._callbacks={};this._comments={};},setCommentState:function(reviewID,commentID,commentType,state){var comment=this._getComment(reviewID,commentID,commentType);this._requestState(comment,state);},registerCallback:function(commentID,callback){if(!this._callbacks[commentID]){this._callbacks[commentID]=[];}
this._callbacks[commentID].push(callback);},_getComment:function(reviewID,commentID,commentType){if(!this._comments[commentID]){var comment=null,reviewRequest=this.get('reviewRequest');if(commentType==="diff_comments"){comment=reviewRequest.createReview(reviewID).createDiffComment(commentID);}else if(commentType==="screenshot_comments"){comment=reviewRequest.createReview(reviewID).createScreenshotComment(commentID);}else if(commentType==="file_attachment_comments"){comment=reviewRequest.createReview(reviewID).createFileAttachmentComment(commentID);}else{console.log("getComment received unexpected context type '%s'",commentType);}
this._comments[commentID]=comment;}
return this._comments[commentID];}, _requestState:function(comment,state){var self=this;comment.ready(function(){var oldIssueStatus=comment.issue_status;comment.issue_status=state;comment.save({success:function(rsp){var rspComment=(rsp.diff_comment||rsp.file_attachment_comment||rsp.screenshot_comment);self._notifyCallbacks(comment.id,comment.issue_status,oldIssueStatus,rspComment.timestamp);if(rsp.last_activity_time){self.get('reviewRequest').markUpdated(rsp.last_activity_time);}}});});},_notifyCallbacks:function(commentID,issueStatus,oldIssueStatus,lastUpdated){_.each(this._callbacks[commentID],function(callback){callback(issueStatus,oldIssueStatus,lastUpdated);});}});RB.FileAttachmentCommentBlock=RB.AbstractCommentBlock.extend({defaults:_.defaults({fileAttachmentID:null},RB.AbstractCommentBlock.prototype.defaults),serializedFields:[],createComment:function(id){var review=gReviewRequest.createReview(),comment=review.createFileAttachmentComment(id,this.get('fileAttachmentID'));_.extend(comment.extra_data,_.pick(this.attributes,this.serializedFields));return comment;}});RB.FileAttachmentReviewable=RB.AbstractReviewable.extend({defaults:_.defaults({caption:'',fileAttachmentID:null},RB.AbstractReviewable.prototype.defaults),reviewableIDField:'fileAttachmentID',addCommentBlocks:function(serializedComments){this.commentBlocks.add(_.extend({fileAttachmentID:this.get('fileAttachmentID'),serializedComments:serializedComments||[]},this.commentBlockModel.prototype.parse(_.pick(serializedComments[0],this.commentBlockModel.prototype.serializedFields))));}});RB.RegionCommentBlock=RB.FileAttachmentCommentBlock.extend({defaults:_.defaults({x:null,y:null,width:null,height:null},RB.AbstractCommentBlock.prototype.defaults),serializedFields:['x','y','width','height'],parse:function(fields){fields.x=parseInt(fields.x,10)||undefined;fields.y=parseInt(fields.y,10)||undefined;fields.width=parseInt(fields.width,10)||undefined;fields.height=parseInt(fields.height,10)||undefined;return fields;}});RB.ImageReviewable=RB.FileAttachmentReviewable.extend({defaults:_.defaults({imageURL:''},RB.FileAttachmentReviewable.prototype.defaults),commentBlockModel:RB.RegionCommentBlock});RB.ScreenshotCommentBlock=RB.AbstractCommentBlock.extend({defaults:_.defaults({screenshotID:null,x:null,y:null,width:null,height:null},RB.AbstractCommentBlock.prototype.defaults),createComment:function(id){return gReviewRequest.createReview().createScreenshotComment(id,this.get('screenshotID'),this.get('x'),this.get('y'),this.get('width'),this.get('height'));}});RB.ScreenshotReviewable=RB.AbstractReviewable.extend({defaults:_.defaults({caption:'',imageURL:'',screenshotID:null},RB.AbstractReviewable.prototype.defaults),commentBlockModel:RB.ScreenshotCommentBlock,reviewableIDField:'screenshotID',addCommentBlocks:function(serializedComments){this.commentBlocks.add({screenshotID:this.get('screenshotID'),x:serializedComments[0].x,y:serializedComments[0].y,width:serializedComments[0].w,height:serializedComments[0].h,serializedComments:serializedComments||[]});}});RB.AbstractCommentBlockView=Backbone.View.extend({events:{'click':'_onClicked'},dispose:function(){this.remove();this._$tooltip.remove();},render:function(){this._$tooltip=$.tooltip(this.$el,{side:'lrbt'}).addClass('comments');this.renderContent();this.model.on('change:draftComment',this._onDraftCommentChanged,this);this._onDraftCommentChanged();this._updateTooltip();return this;},positionCommentDlg:function(commentDlg){commentDlg.positionToSide(this.$el,{side:'r',fitOnScreen:true});},notify:function(text,cb){var offset=this.$el.offset(),bubble=$('<div/>').addClass('bubble').appendTo(this.$el).text(text);bubble.css('opacity',0).move(Math.round((this.$el.width()-bubble.width())/2),Math.round((this.$el.height()-bubble.height())/2)).animate({top:'-=10px',opacity:0.8},350,'swing').delay(1200).animate({top:'+=10px',opacity:0},350,'swing',function(){bubble.remove();if(_.isFunction(cb)){cb();}});},_updateTooltip:function(){var list=$('<ul/>'),draftComment=this.model.get('draftComment');function addEntry(comment){return $('<li>').text(comment.text.truncate()).appendTo(list);}
if(draftComment){addEntry(draftComment).addClass("draft");}
_.each(this.model.get('serializedComments'),addEntry);this._$tooltip.empty().append(list);},_onDraftCommentChanged:function(){var self=this,$el=this.$el,comment=this.model.get('draftComment');if(!comment){$el.removeClass('draft');return;}
$.event.add(comment,'textChanged',_.bind(this._updateTooltip,this));$.event.add(comment,'deleted',function(){$el.queue(function(){self.notify('Comment Deleted',function(){$el.dequeue();});});});$.event.add(comment,'destroyed',function(){if(self.model.isEmpty()){$el.fadeOut(350,function(){self.dispose();})}else{$el.removeClass('draft');self._updateTooltip();}});$.event.add(comment,'saved',function(){self._updateTooltip();self.notify('Comment Saved');showReviewBanner();});$el.addClass('draft');},_onClicked:function(){this.trigger('clicked');}});RB.AbstractReviewableView=Backbone.View.extend({commentBlockView:null,commentsListName:null,initialize:function(){console.assert(this.commentBlockView,'commentBlockView must be defined by the subclass');console.assert(this.commentsListName,'commentsListName must be defined by the subclass');this.commentDlg=gCommentDlg;},render:function(){this.renderContent();this.model.commentBlocks.each(this._addCommentBlockView,this);this.model.commentBlocks.on('add',this._addCommentBlockView,this);return this;},renderContent:function(){},createAndEditCommentBlock:function(opts){var idField=this.model.reviewableIDField;this.once('commentBlockViewAdded',function(commentBlockView){this.showCommentDlg(commentBlockView);},this);opts[idField]=this.model.get(idField);this.model.commentBlocks.add(opts);},showCommentDlg:function(commentBlockView){this.commentDlg.one('close',_.bind(function(){var commentBlock=commentBlockView.model;commentBlock.ensureDraftComment();this.commentDlg.setDraftComment(commentBlock.get('draftComment')).setCommentsList(commentBlock.get('serializedComments'),this.commentsListName);commentBlockView.positionCommentDlg(this.commentDlg);this.commentDlg.open();},this)).close();},_addCommentBlockView:function(commentBlock){var commentBlockView=new this.commentBlockView({model:commentBlock});commentBlockView.on('clicked',function(){this.showCommentDlg(commentBlockView);},this);commentBlockView.render();this.trigger('commentBlockViewAdded',commentBlockView);}});RB.FileAttachmentReviewableView=RB.AbstractReviewableView.extend({commentsListName:'file_attachment_comments'});RB.IssueSummaryTableView=Backbone.View.extend({events:{'change .filter':'_onFilterChanged','click thead th':'_onHeaderClicked','click .summary-anchor':'_onAnchorClicked'}, stateToSelectorMap:{open:".open",dropped:".dropped",resolved:".resolved",all:""},initialize:function(){this.statusFilterState="open";this.reviewerFilterState="all"; this.reviewerToSelectorMap={all:""};},render:function(){this._$table=this.$el.find('table');this._$thead=this._$table.find('thead');this._$tbody=this._$table.find('tbody');this._buildReviewerFilterMap();this._checkNoIssues();this._uncollapseTarget();},setVisibility:function(entry,status){if(this.statusFilterState!==status&&this.statusFilterState!=='all'){entry.addClass('hidden');}else{entry.removeClass('hidden');}},updateCounters:function(old_status,new_status){var old_counter=$('#'+old_status+'-counter'),new_counter=$('#'+new_status+'-counter');old_counter.text(parseInt(old_counter.text(),10)-1);new_counter.text(parseInt(new_counter.text(),10)+1);},updateStatus:function(entry,old_status,new_status){entry.removeClass(old_status).addClass(new_status).find('.status').text(new_status);this.setVisibility(entry,new_status);this._checkNoIssues();},updateTimeStamp:function(entry,timestamp){entry.find(".last-updated").attr("timestamp",new Date(timestamp).getTime()).text(timestamp);},_onFilterChanged:function(){ $('.issue'+this.stateToSelectorMap[this.statusFilterState]+
this.reviewerToSelectorMap[this.reviewerFilterState]).toggleClass("hidden"); this.statusFilterState=$("#issue-state-filter").val();this.reviewerFilterState=$("#issue-reviewer-filter").val(); $('.issue'+this.stateToSelectorMap[this.statusFilterState]+
this.reviewerToSelectorMap[this.reviewerFilterState]).toggleClass("hidden");this._checkNoIssues();},_onHeaderClicked:function(event){if(this._$tbody.find('tr.issue:visible').length!==0){var $header=$(event.srcElement);this._sortByCol($header.parent().children().index(event.srcElement)+1);}
return false;},_onAnchorClicked:function(event){event.stopPropagation();var issueId='#comment-'+$(event.srcElement).attr("issue-id")+'-issue';$(issueId).closest(".box").removeClass("collapsed");},_checkNoIssues:function(){this._$tbody.find('tr.no-issues').remove();this._$thead.show();if(this._$tbody.find('tr.issue:visible').length===0){var text="There are no "+this.statusFilterState+" issues";if(this.reviewerFilterState!=="all"){text+=" from "+this.reviewerFilterState;}
this._$thead.hide();this._$tbody.append($('<tr>').addClass('no-issues').append($('<td>').attr("colspan",5).append($('<i>').text(text))));}},_sortByCol:function(colIndex){this._$tbody.html($('.issue').sort(function(a,b){var firstElement=$(a).find('td:nth-child('+colIndex+')'),secondElement=$(b).find('td:nth-child('+colIndex+')'),firstElementText=firstElement.text().toLowerCase(),secondElementText=secondElement.text().toLowerCase();if(firstElement.attr('timestamp')){return parseInt(firstElement.attr('timestamp'),10)-
parseInt(secondElement.attr('timestamp'),10);}else if(firstElement.hasClass('comment-id')){var firstText=firstElementText.split(" "),secondText=secondElementText.split(" ");if(firstText[0]>secondText[0]){return 1;}else if(firstText[0]<secondText[0]){return-1;}else{return parseInt(firstText[1],10)-
parseInt(secondText[1],10)}}else if(firstElementText>secondElementText){return 1;}else if(firstElementText===secondElementText){return 0;}else{return-1;}}));}, _buildReviewerFilterMap:function(){var self=this;this._$tbody.find('.issue').each(function(){var reviewer=$(this).attr('reviewer');if(!_.has(self.reviewerToSelectorMap,reviewer)){self.reviewerToSelectorMap[reviewer]='[reviewer="'+reviewer+'"]';$('#issue-reviewer-filter').append($('<option>').text(reviewer).val(reviewer));}});},_uncollapseTarget:function(){var hash=window.location.hash;if(hash.indexOf("comment")>0){var comment_name=hash.toString().substring(1),target_box=$('a[name='+comment_name+']').closest(".box");if(target_box.hasClass('collapsed')){target_box.removeClass("collapsed"); window.location=window.location;}}}});RB.RegionCommentBlockView=RB.AbstractCommentBlockView.extend({className:'selection',initialize:function(){this.on('change:x change:y change:width change:height',this._updateDimensions,this);},renderContent:function(){this._updateDimensions();this._$flag=$('<div/>').addClass('selection-flag').appendTo(this.$el);this.model.on('change:count',this._updateCount,this);this._updateCount();},positionCommentDlg:function(commentDlg){commentDlg.positionToSide(this._$flag,{side:'b',fitOnScreen:true});},_updateDimensions:function(){var model=this.model;this.$el.move(model.get('x'),model.get('y'),'absolute').width(model.get('width')).height(model.get('height'));},_updateCount:function(){this._$flag.text(this.model.get('count'));}});RB.ImageReviewableView=RB.FileAttachmentReviewableView.extend({className:'image-review-ui',commentBlockView:RB.RegionCommentBlockView,events:{'mousedown .selection-container':'_onMouseDown','mouseup .selection-container':'_onMouseUp','mousemove .selection-container':'_onMouseMove'},initialize:function(){RB.AbstractReviewableView.prototype.initialize.call(this);_.bindAll(this,'_adjustPos');this._activeSelection={};this.on('commentBlockViewAdded',function(commentBlockView){this._$selectionArea.append(commentBlockView.$el);},this);},renderContent:function(){var self=this;this._$image=$('<img/>').attr({caption:this.model.get('caption'),src:this.model.get('imageURL')});this._$selectionArea=$('<div/>').addClass('selection-container').proxyTouchEvents();this._$selectionRect=$('<div/>').addClass('selection-rect').prependTo(this._$selectionArea).proxyTouchEvents().hide();this.$el
.hover(function(){self._$selectionArea.show();},function(){if(self._$selectionRect.is(':hidden')&&self.commentDlg.is(':hidden')){self._$selectionArea.hide();}}).append(this._$selectionArea).append(this._$image);$(window).resize(this._adjustPos).load(this._adjustPos);return this;},_onMouseDown:function(evt){if(evt.which===1&&this.commentDlg.is(':hidden')&&!$(evt.target).hasClass('selection-flag')){var offset=this._$selectionArea.offset();this._activeSelection.beginX=evt.pageX-Math.floor(offset.left)-1;this._activeSelection.beginY=evt.pageY-Math.floor(offset.top)-1;this._$selectionRect.move(this._activeSelection.beginX,this._activeSelection.beginY).width(1).height(1).show();if(this._$selectionRect.is(':hidden')){this.commentDlg.hide();}
return false;}},_onMouseUp:function(evt){if(this.commentDlg.is(':hidden')&&this._$selectionRect.is(":visible")){var width=this._$selectionRect.width(),height=this._$selectionRect.height(),offset=this._$selectionRect.position();evt.stopPropagation();this._$selectionRect.hide();if(width>5&&height>5){this.createAndEditCommentBlock({x:Math.floor(offset.left),y:Math.floor(offset.top),width:width,height:height});}}},_onMouseMove:function(evt){if(this.commentDlg.is(':hidden')&&this._$selectionRect.is(":visible")){var offset=this._$selectionArea.offset(),x=evt.pageX-Math.floor(offset.left)-1,y=evt.pageY-Math.floor(offset.top)-1;this._$selectionRect.css(this._activeSelection.beginX<=x?{left:this._activeSelection.beginX,width:x-this._activeSelection.beginX}:{left:x,width:this._activeSelection.beginX-x}).css(this._activeSelection.beginY<=y?{top:this._activeSelection.beginY,height:y-this._activeSelection.beginY}:{top:y,height:this._activeSelection.beginY-y});return false;}},_adjustPos:function(){var offset=this._$image.position();offset.left+=this._$image.getExtents("m","l");if($.browser.msie&&$.browser.version===6){offset.left-=self.getExtents("mp","l");}
this._$selectionArea.width(this._$image.width()).height(this._$image.height()).css("left",offset.left);}});var BACKWARD=-1;var FORWARD=1;var INVALID=-1;var DIFF_SCROLLDOWN_AMOUNT=100;var VISIBLE_CONTEXT_SIZE=5;var ANCHOR_COMMENT=1;var ANCHOR_FILE=2;var ANCHOR_CHUNK=4;var gDiff,gCollapseButtons=[];var gActions=[{ keys:"aAKP<m",onPress:function(){scrollToAnchor(GetNextAnchor(BACKWARD,ANCHOR_FILE));}},{ keys:"fFJN>",onPress:function(){scrollToAnchor(GetNextAnchor(FORWARD,ANCHOR_FILE));}},{ keys:"sSkp,,",onPress:function(){scrollToAnchor(GetNextAnchor(BACKWARD,ANCHOR_CHUNK|ANCHOR_FILE));}},{ keys:"dDjn..",onPress:function(){scrollToAnchor(GetNextAnchor(FORWARD,ANCHOR_CHUNK|ANCHOR_FILE));}},{ keys:unescape("%0D"),onPress:function(){scrollToAnchor($(gAnchors[gSelectedAnchor]));}},{ keys:"[x",onPress:function(){scrollToAnchor(GetNextAnchor(BACKWARD,ANCHOR_COMMENT));}},{ keys:"]c",onPress:function(){scrollToAnchor(GetNextAnchor(FORWARD,ANCHOR_COMMENT));}},{ keys:"gu;",onPress:function(){}},{ keys:"GU:",onPress:function(){}}];var gSelectedAnchor=INVALID;var gFileAnchorToId={};var gInterdiffFileAnchorToId={};var gAnchors=$();var gHiddenComments={};var gDiffHighlightBorder=null;var gStartAtAnchor=null;function DiffCommentBlock(beginRow,endRow,beginLineNum,endLineNum,comments){var self=this;var table=beginRow.parents("table:first");var fileid=table[0].id;this.filediff=gFileAnchorToId[fileid];this.interfilediff=gInterdiffFileAnchorToId[fileid];this.beginLineNum=beginLineNum;this.endLineNum=endLineNum;this.beginRow=beginRow;this.endRow=endRow;this.comments=[];this.draftComment=null;this.el=$("<span/>").addClass("commentflag").append($("<span/>").addClass("commentflag-shadow")).click(function(){self.showCommentDlg();return false;});$(window).on("resize",function(evt){self.updateSize();});var innerFlag=$("<span/>").addClass("commentflag-inner").appendTo(this.el);this.countEl=$("<span/>").appendTo(innerFlag);if($.browser.msie&&$.browser.version==6){this.tooltip=$("<div/>");}else{this.tooltip=$.tooltip(this.el,{side:"rb"}).addClass("comments");}
this.anchor=$("<a/>").attr("name","file"+this.filediff.id+"line"+this.beginLineNum).addClass("comment-anchor").appendTo(this.el);if(comments&&comments.length>0){for(var i in comments){var comment=comments[i];if(comment.text){comment.text=$("<div/>").html(comment.text).text();}
if(comment.localdraft){this._createDraftComment(comment.comment_id,comment.text);}else{this.comments.push(comment);}}}else{this._createDraftComment();}
this.updateCount();this.updateTooltip();this.updateSize();this.beginRow[0].cells[0].appendChild(this.el[0]);}
$.extend(DiffCommentBlock.prototype,{notify:function(text){var offset=this.el.offset();var bubble=$("<div/>").addClass("bubble").text(text).appendTo(this.el);bubble.css({left:this.el.width(),top:0,opacity:0}).animate({top:"-=10px",opacity:0.8},350,"swing").delay(1200).animate({top:"+=10px",opacity:0},350,"swing",function(){bubble.remove();});},updateTooltip:function(){this.tooltip.empty();var list=$("<ul/>");if(this.draftComment){$("<li/>").text(this.draftComment.text.truncate()).addClass("draft").appendTo(list);}
for(var i=0;i<this.comments.length;i++){$("<li/>").text(this.comments[i].text.truncate()).appendTo(list);}
list.appendTo(this.tooltip);},updateCount:function(){var count=this.comments.length;if(this.draftComment){count++;}
this.count=count;this.countEl.html(this.count);},updateSize:function(){var extents=this.el.getExtents("m","t")||-4;this.el.css("height",this.endRow.offset().top+this.endRow.outerHeight()-
this.beginRow.offset().top-extents);},showCommentDlg:function(){var self=this;gCommentDlg.one("close",function(){self._createDraftComment();gCommentDlg.setDraftComment(self.draftComment).setCommentsList(self.comments,"diff_comments").css({left:$(document).scrollLeft()+
($(window).width()-gCommentDlg.width())/2,top:self.endRow.offset().top+
self.endRow.height()}).open(self.el);}).close();},_createDraftComment:function(id,text){if(this.draftComment!=null){return;}
var self=this;var el=this.el;var comment=gReviewRequest.createReview().createDiffComment(id,this.filediff,this.interfilediff,this.beginLineNum,this.endLineNum);if(text){comment.text=text;}
$.event.add(comment,"textChanged",function(){self.updateTooltip();});$.event.add(comment,"deleted",function(){self.notify("Comment Deleted");});$.event.add(comment,"destroyed",function(){self.draftComment=null;if(self.comments.length==0){el.fadeOut(350,function(){el.remove();})
self.anchor.remove();}else{el.removeClass("draft");self.updateCount();self.updateTooltip();}});$.event.add(comment,"saved",function(){self.updateCount();self.updateTooltip();self.notify("Comment Saved");showReviewBanner();});this.draftComment=comment;el.addClass("draft");}});$.fn.diffFile=function(lines,key){return this.each(function(){var self=$(this);var selection={begin:null,beginNum:0,end:null,endNum:0,lastSeenIndex:0};var ghostCommentFlag=$("<span/>").addClass("commentflag").addClass("ghost-commentflag").append($("<span class='commentflag-shadow'/>")).append($("<span class='commentflag-inner'/>")).mousedown(function(e){self.triggerHandler("mousedown",e);}).mouseup(function(e){self.triggerHandler("mouseup",e);}).mouseover(function(e){self.triggerHandler("mouseover",e);}).mouseout(function(e){self.triggerHandler("mouseout",e);}).hide().appendTo("body");var ghostCommentFlagCell=null;self.mousedown(function(e){var node=e.target;if(ghostCommentFlagCell!=null){node=ghostCommentFlagCell[0];}
if(isLineNumCell(node)){beginSelection($(node.parentNode));return false;}
return true;}).mouseup(function(e){var node=e.target;if(ghostCommentFlagCell!=null){node=ghostCommentFlagCell[0];}
if(isLineNumCell(node)){endSelection(getActualLineNumCell($(node)).parent());}else{var tbody=$(node).parents("tbody:first");if(tbody.length>0&&(tbody.hasClass("delete")||tbody.hasClass("insert")||tbody.hasClass("replace"))){gotoAnchor($("a:first",tbody).attr("name"),true);}}
resetSelection();return false;}).mouseover(function(e){var node=getActualLineNumCell($(e.target));var row=node.parent();if(isLineNumCell(node[0])){addRowToSelection(row);}else if(ghostCommentFlagCell!=null&&node[0]!=ghostCommentFlagCell[0]){row.removeClass("selected");}}).mouseout(function(e){var relTarget=e.relatedTarget,node=getActualLineNumCell($(e.target));if(relTarget!=ghostCommentFlag[0]){ghostCommentFlag.hide();ghostCommentFlagCell=null;}
if(selection.begin!=null){if(relTarget!=null&&isLineNumCell(relTarget)){removeOldRowsFromSelection($(relTarget.parentNode));}}else if(node!=null&&isLineNumCell(node[0])){node.parent().removeClass("selected");}}).on({"touchmove":function(e){var firstTouch=e.originalEvent.targetTouches[0];var target=document.elementFromPoint(firstTouch.pageX,firstTouch.pageY);var node=getActualLineNumCell($(target));var row=node.parent();if(selection.lastSeenIndex==row[0].rowIndex){return;}
if(isLineNumCell(node[0])){var row=node.parent();removeOldRowsFromSelection(row);addRowToSelection(row);}},"touchcancel":function(e){resetSelection();}}).proxyTouchEvents("touchstart touchend");addCommentFlags(self,lines,key);function beginSelection(row){selection.begin=selection.end=row;selection.beginNum=selection.endNum=parseInt(row.attr('line'),10);selection.lastSeenIndex=row[0].rowIndex;row.addClass("selected");self.disableSelection();}
function endSelection(row){row.removeClass("selected");if(selection.beginNum==selection.endNum){var commentFlag=row.find(".commentflag");if(commentFlag.length==1){commentFlag.click()
return;}}
var commentBlock=new DiffCommentBlock(selection.begin,selection.end,selection.beginNum,selection.endNum);commentBlock.showCommentDlg();}
function addRowToSelection(row){if(selection.begin!=null){var linenum=parseInt(row.attr("line"),10);if(linenum<selection.beginNum){selection.beginNum=linenum;selection.begin=row;}else if(linenum>selection.beginNum){selection.end=row;selection.endNum=linenum;}
var min=Math.min(selection.lastSeenIndex,row[0].rowIndex);var max=Math.max(selection.lastSeenIndex,row[0].rowIndex);for(var i=min;i<=max;i++){$(self[0].rows[i]).addClass("selected");}
selection.lastSeenIndex=row[0].rowIndex;}else{var lineNumCell=row[0].cells[0];if($(".commentflag",lineNumCell).length==0){ghostCommentFlag.css("top",row.offset().top-1).show().parent().removeClass("selected");ghostCommentFlagCell=$(row[0].cells[0]);}
row.addClass("selected");}}
function removeOldRowsFromSelection(row){var destRowIndex=row[0].rowIndex;if(destRowIndex>=selection.begin[0].rowIndex){for(var i=selection.lastSeenIndex;i>destRowIndex;i--){$(self[0].rows[i]).removeClass("selected");}
selection.lastSeenIndex=destRowIndex;}}
function resetSelection(){if(selection.begin!=null){var rows=self[0].rows;for(var i=selection.begin[0].rowIndex;i<=selection.end[0].rowIndex;i++){$(rows[i]).removeClass("selected");}
selection.begin=selection.end=null;selection.beginNum=selection.endNum=0;selection.rows=[];}
ghostCommentFlagCell=null;self.enableSelection();}
function isLineNumCell(cell){return(cell.tagName=="TH"&&cell.parentNode.getAttribute('line'));}
function getActualLineNumCell(node){if(node.hasClass("commentflag")){if(node[0]==ghostCommentFlag[0]){node=ghostCommentFlagCell;}else{node=node.parent();}}
return node;}});};$.fn.highlightChunk=function(){var firstHighlight=false;if(!gDiffHighlightBorder){var borderEl=$("<div/>").addClass("diff-highlight-border").css("position","absolute");gDiffHighlightBorder={top:borderEl.clone().appendTo("#diffs"),bottom:borderEl.clone().appendTo("#diffs"),left:borderEl.clone().appendTo("#diffs"),right:borderEl.clone().appendTo("#diffs")};firstHighlight=true;}
var el=this.parents("tbody:first, thead:first");var borderWidth=gDiffHighlightBorder.left.width();var borderHeight=gDiffHighlightBorder.top.height();var borderOffsetX=borderWidth/2;var borderOffsetY=borderHeight/2;if($.browser.msie&&$.browser.version<=8){borderOffsetY=-borderOffsetY;if($.browser.msie&&$.browser.version==8){borderOffsetX=-borderOffsetX;}}
var updateQueued=false;var oldLeft;var oldTop;var oldWidth;var oldHeight;function updatePosition(event){if(event&&event.target&&event.target!=window&&!event.target.getElementsByTagName){return;}
var offset=el.position();if(!offset){return;}
var left=Math.round(offset.left);var top=Math.round(offset.top);var width=el.outerWidth();var height=el.outerHeight();if(left==oldLeft&&top==oldTop&&width==oldWidth&&height==oldHeight){return;}
var outerHeight=height+borderHeight;var outerWidth=width+borderWidth;var outerLeft=left-borderOffsetX;var outerTop=top-borderOffsetY;gDiffHighlightBorder.left.css({left:outerLeft,top:outerTop,height:outerHeight});gDiffHighlightBorder.top.css({left:outerLeft,top:outerTop,width:outerWidth});gDiffHighlightBorder.right.css({left:outerLeft+width,top:outerTop,height:outerHeight});gDiffHighlightBorder.bottom.css({left:outerLeft,top:outerTop+height,width:outerWidth});oldLeft=left;oldTop=top;oldWidth=width;oldHeight=height;updateQueued=false;}
function queueUpdatePosition(event){if(!updateQueued){updateQueued=true;setTimeout(function(){updatePosition(event);},50);}}
$(document).on("DOMNodeInserted.highlightChunk DOMNodeRemoved.highlightChunk",queueUpdatePosition);$(window).on("resize.highlightChunk",updatePosition);if(firstHighlight){queueUpdatePosition();}else{updatePosition();}
return this;};function gotoAnchor(name,scroll){return scrollToAnchor($("a[name='"+name+"']"),scroll||false);}
function findLineNumRow(table,linenum,startRow,endRow){var row=null;var row_offset=1;if(table.rows.length-row_offset>linenum){row=table.rows[row_offset+linenum];if(row!=null&&parseInt(row.getAttribute('line'),10)==linenum){return row;}}
if(startRow){ startRow-=row_offset;}
var low=startRow||1;var high=Math.min(endRow||table.rows.length,table.rows.length);if(endRow!=undefined&&endRow<table.rows.length){if(parseInt(table.rows[endRow].getAttribute('line'),10)==linenum){return table.rows[endRow];}}else if(row!=null){high=Math.min(high,row_offset+linenum);}
for(var i=Math.round((low+high)/2);low<high-1;){row=table.rows[row_offset+i];if(!row){high--;i=Math.round((low+high)/2);continue;}
var value=parseInt(row.getAttribute('line'),10);if(!value){var found=false;for(var k=1;k<=(high-low)/2;k++){row=table.rows[row_offset+i+k];if(row&&parseInt(row.getAttribute('line'),10)){i=i+k;found=true;break;}else{row=table.rows[row_offset+i-k];if(row&&parseInt(row.getAttribute('line'),10)){i=i-k;found=true;break;}}}
if(found){value=parseInt(row.getAttribute('line'),10);}else{return null;}}
var guessRowNum=linenum-value+row_offset+i;if(guessRowNum>=0&&guessRowNum<table.rows.length){var guessRow=table.rows[guessRowNum];if(guessRow&&parseInt(guessRow.getAttribute('line'),10)==linenum){return guessRow;}}
var oldHigh=high;var oldLow=low;if(value>linenum){high=i;}else if(value<linenum){low=i;}else{return row;}
if(oldHigh==high&&oldLow==low){break;}
i=Math.round((low+high)/2);}
return null;}
function addCommentFlags(table,lines,key){var remaining={};var prevBeginRowIndex=undefined;for(var i in lines){var line=lines[i];var numLines=line.num_lines;var beginLineNum=line.linenum;var endLineNum=beginLineNum+numLines-1;var beginRow=findLineNumRow(table[0],beginLineNum,prevBeginRowIndex);if(beginRow!=null){prevBeginRowIndex=beginRow.rowIndex;var endRow=(endLineNum==beginLineNum?beginRow:findLineNumRow(table[0],endLineNum,prevBeginRowIndex,prevBeginRowIndex+numLines-1));new DiffCommentBlock($(beginRow),$(endRow||beginRow),beginLineNum,endLineNum,line.comments);}else{remaining[beginLineNum]=line;}}
gHiddenComments[key]=remaining;}
RB.expandChunk=function(review_base_url,fileid,filediff_id,revision,interdiff_revision,file_index,chunk_index,lines_of_context,link){gDiff.getDiffFragment(review_base_url,fileid,filediff_id,revision,interdiff_revision,file_index,chunk_index,lines_of_context,function(html){var tbody=$(link).parents('tbody'),table=tbody.parent(),key='file'+filediff_id,$scrollAnchor,tbodyID,scrollAnchorSel,scrollOffsetTop;if($(link).hasClass('diff-collapse-btn')){$scrollAnchor=$(link);}else{$scrollAnchor=tbody;if(lines_of_context===0){tbodyID=/collapsed-(.*)/.exec($scrollAnchor[0].id)[1];tbodySel='img.diff-collapse-btn';}else{tbodyID=$scrollAnchor[0].id;}}
scrollOffsetTop=$scrollAnchor.offset().top-$(window).scrollTop();tbody.prev('.diff-header').remove();tbody.next('.diff-header').remove();tbody.prev('.loaded').remove();tbody.next('.loaded').remove();tbody.replaceWith(html);addCommentFlags(table,gHiddenComments[key],key);if(tbodyID){var el=document.getElementById(tbodyID);if(el){$scrollAnchor=$(el);if(scrollAnchorSel){$scrollAnchor=$scrollAnchor.find(scrollAnchorSel);}
if($scrollAnchor.length>0){$(window).scrollTop($scrollAnchor.offset().top-
scrollOffsetTop);}}}
gCollapseButtons=$('table.sidebyside .diff-collapse-btn');updateCollapseButtonPos();$(gAnchors[gSelectedAnchor]).highlightChunk();});}
function updateCollapseButtonPos(){var windowTop=$(window).scrollTop(),windowHeight=$(window).height(),len=gCollapseButtons.length,i;for(i=0;i<len;i++){var button=$(gCollapseButtons[i]),parentEl=button.parents('tbody'),parentOffset=parentEl.offset(),parentTop=parentOffset.top,parentHeight=parentEl.height(),btnRight=button.data('rb-orig-right');if(btnRight===undefined){btnRight=parseInt(button.css('right'),10);button.data('rb-orig-right',btnRight);}
if(parentTop>=windowTop+windowHeight){break;}else if(parentTop+parentHeight<=windowTop){}else{var buttonHeight=button.outerHeight();if(windowTop>=parentTop&&windowTop+windowHeight<=parentTop+parentHeight){var btnParent=button.parent(),parentLeft=btnParent.offset().left;button.css({position:'fixed',left:parentLeft+btnParent.innerWidth()+
btnRight-parentOffset.left,top:Math.round((windowHeight-buttonHeight)/2)});break;}else{var y1=Math.max(windowTop,parentTop),y2=Math.min(windowTop+windowHeight,parentTop+parentHeight);button.css({position:'absolute',left:null,top:y1-parentTop+
Math.round((y2-y1-buttonHeight)/2)});}}}}
function scrollToAnchor(anchor,noscroll){if(anchor.length==0){return false;}
if(anchor.parent().is(":hidden")){return false;}
if(!noscroll){$(window).scrollTop(anchor.offset().top-DIFF_SCROLLDOWN_AMOUNT);}
anchor.highlightChunk();for(var i=0;i<gAnchors.length;i++){if(gAnchors[i]==anchor[0]){gSelectedAnchor=i;break;}}
return true;}
function GetNextAnchor(dir,anchorType){for(var anchor=gSelectedAnchor+dir;anchor>=0&&anchor<gAnchors.length;anchor=anchor+dir){var anchorEl=$(gAnchors[anchor]);if(((anchorType&ANCHOR_COMMENT)&&anchorEl.hasClass("comment-anchor"))||((anchorType&ANCHOR_FILE)&&anchorEl.hasClass("file-anchor"))||((anchorType&ANCHOR_CHUNK)&&anchorEl.hasClass("chunk-anchor"))){return anchorEl;}}
return $([]);}
function updateAnchors(table){gAnchors=gAnchors.add($("a[name]",table));if(gSelectedAnchor==-1&&gAnchors.length>0){gSelectedAnchor=0;$(gAnchors[gSelectedAnchor]).highlightChunk();}}
RB.loadFileDiff=function(review_base_url,filediff_id,filediff_revision,interfilediff_id,interfilediff_revision,file_index,comment_counts){if($("#file"+filediff_id).length==1){setupFileDiff();}else{$.funcQueue("diff_files").add(function(){gDiff.getDiffFile(review_base_url,filediff_id,filediff_revision,interfilediff_id,interfilediff_revision,file_index,onFileLoaded);});}
function onFileLoaded(xhr){$("#file_container_"+filediff_id).replaceWith(xhr.responseText);setupFileDiff();}
function setupFileDiff(){var key="file"+filediff_id;gFileAnchorToId[key]={'id':filediff_id,'revision':filediff_revision};if(interfilediff_id){gInterdiffFileAnchorToId[key]={'id':interfilediff_id,'revision':interfilediff_revision};}
var diffTable=$("#file"+filediff_id);diffTable.diffFile(comment_counts,key);updateAnchors(diffTable);if(gStartAtAnchor!=null){var anchor=$("a[name='"+gStartAtAnchor+"']");if(anchor.length!=0){scrollToAnchor(anchor);gStartAtAnchor=null;}}
$.funcQueue("diff_files").next();}}
function toggleWhitespaceChunks()
{var tables=$("table.sidebyside");var chunks=tables.children("tbody.whitespace-chunk");chunks.toggleClass("replace");chunks.each(function(){var target=this.id.split("chunk")[1];$("ol.index a[href=#"+target+"]").toggleClass("dimmed");});chunks.children(":first-child").toggleClass("first");chunks.children(":last-child").toggleClass("last");tables.find("tbody tr.whitespace-line").toggleClass("dimmed");$(".review-request ul.controls li.ws").toggle();tables.children("tbody.whitespace-file").toggle().siblings("tbody").toggle();}
function showExtraWhitespace()
{if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(";");for(var i in cookies){var cookie=jQuery.trim(cookies[i]);if(cookie=="show_ew=false"){return false;}}}
return true;}
function setExtraWhitespace(value)
{document.cookie="show_ew="+value+"; path=/;";}
function toggleExtraWhitespace(init)
{if(init==undefined){toggleExtraWhitespace.show_ew=!toggleExtraWhitespace.show_ew;setExtraWhitespace(toggleExtraWhitespace.show_ew);}
else{toggleExtraWhitespace.show_ew=showExtraWhitespace();if(!toggleExtraWhitespace.show_ew){return;}}
$("#diffs").toggleClass("ewhl");$(".review-request ul.controls li.ew").toggle();}
$(document).ready(function(){if(!window.gRevision){return;}
gDiff=gReviewRequest.createDiff(gRevision,gInterdiffRevision);$(document).keypress(function(evt){if(evt.altKey||evt.ctrlKey||evt.metaKey){return;}
var keyChar=String.fromCharCode(evt.which);for(var i=0;i<gActions.length;i++){if(gActions[i].keys.indexOf(keyChar)!=-1){gActions[i].onPress();return false;}}});$(window).scroll(updateCollapseButtonPos);$(window).resize(updateCollapseButtonPos);$("ul.controls li a.toggleWhitespaceButton").click(function(){toggleWhitespaceChunks();return false;});$("ul.controls li a.toggleExtraWhitespaceButton").click(function(){toggleExtraWhitespace();return false;});toggleExtraWhitespace('init');$("input, textarea").keypress(function(evt){evt.stopPropagation();});var url=document.location.toString();if(url.match("#")){gStartAtAnchor=url.split("#")[1];}
$.funcQueue("diff_files").start();$("table.sidebyside tr td a.moved-to,"+"table.sidebyside tr td a.moved-from").click(function(){var destination=$(this).attr("line");return!scrollToAnchor($("td a[target="+destination+"]",$(this).parents("table")).parent().siblings().andSelf().effect("highlight",{},2000),false);});});this.gCommentDlg=null;this.gReviewRequest=new RB.ReviewRequest(gReviewRequestId,gReviewRequestSitePrefix,gReviewRequestPath);var gEditCount=0;var gPublishing=false;var gPendingSaveCount=0;var gPendingDiffFragments={};var gReviewBanner=$("#review-banner");var gDraftBanner=$("#draft-banner");var gDraftBannerButtons=$("input",gDraftBanner);var gFileAttachmentComments={};var gCommentIssueManager=new RB.CommentIssueManager({reviewRequest:this.gReviewRequest});var issueSummaryTableManager;RB.draftBanner=gDraftBanner;var gEditorCompleteHandlers={'bugs_closed':function(data){if(gBugTrackerURL==""){return data.join(", ");}else{return urlizeList(data,function(item){return gBugTrackerURL.replace("%s",item);});}},'target_groups':function(data){return urlizeList(data,function(item){return item.url;},function(item){return item.name;});},'target_people':function(data){return $(urlizeList(data,function(item){return item.url;},function(item){return item.username;})).addClass("user").user_infobox();},'description':linkifyText,'testing_done':linkifyText};function urlizeList(list,urlFunc,textFunc,postProcessFunc){var str="";for(var i=0;i<list.length;i++){var item=list[i];str+='<a href="';str+=(urlFunc?urlFunc(item):item);str+='">';str+=(textFunc?textFunc(item):item);str+='</a>';if(i<list.length-1){str+=", ";}}
return str;}
function linkifyText(text){text=text.htmlEncode();text=text.replace(/\b([a-z]+:\/\/[\-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*([\-A-Za-z0-9+@#\/%=~_();|]|))/g,function(url){var extra='',parts=url.match(/^(.*)(&[a-z]+;|\))$/),openParen=url.match(/.*\(.*/);if(parts!=null&&openParen==null){url=parts[1];extra=parts[2];}
return'<a target="_blank" href="'+url+'">'+url+'</a>'+extra;});text=text.replace(/(^|\s|&lt;)\/(r\/\d+(\/[\-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_()|])?)/g,'$1<a target="_blank" href="'+SITE_ROOT+'$2">/$2</a>');if(gBugTrackerURL!=""){text=text.replace(/\b(bug|issue) (#([^.\s]+)|#?(\d+))/gi,function(text,m2,m3,bugnum1,bugnum2){var bugnum=bugnum1||bugnum2;return'<a target="_blank" href="'+
gBugTrackerURL.replace("%s",bugnum)+'">'+text+'</a>';});}
return text;}
function setDraftField(field,value){gReviewRequest.setDraftField({field:field,value:value,buttons:gDraftBannerButtons,success:function(rsp){if(rsp.stat=="fail"&&rsp.fields){$('#review-request-warning').delay(6000).fadeOut(400,function(){$(this).hide();});$.each(rsp.fields[field],function(key,value){var size=rsp.fields[field].length;if(key==size-1&&size>1){rsp.fields[field][key]="and '"+value+"'";}else{rsp.fields[field][key]="'"+value+"'";}});var message=rsp.fields[field].join(", ");if(rsp.fields[field].length==1){if(field=="target_groups"){message="Group "+message+" does not exist.";}else{message="User "+message+" does not exist.";}}else{if(field=="target_groups"){message="Groups "+message+" do not exist.";}else{message="Users "+message+" do not exist.";}}
$("#review-request-warning").show().find("td").html(message);}
var func=gEditorCompleteHandlers[field];if($.isFunction(func)){$("#"+field).empty().html(func(rsp['draft'][field]));}
gDraftBanner.show();if(gPublishing){gPendingSaveCount--;if(gPendingSaveCount==0){publishDraft();}}},error:function(){gPublishing=false;}});}
$.fn.reviewsAutoComplete=function(options){return this.each(function(){$(this).rbautocomplete({formatItem:function(data){var s=data[options.nameKey];if(options.descKey&&data[options.descKey]){s+=" <span>("+data[options.descKey]+")</span>";}
return s;},matchCase:false,multiple:true,parse:function(data){var items=data[options.fieldName],parsed=[];for(var i=0;i<items.length;i++){var value=items[i];parsed.push({data:value,value:value[options.nameKey],result:value[options.nameKey]});}
return parsed;},url:SITE_ROOT+gReviewRequestSitePrefix+"api/"+options.fieldName+"/",extraParams:options.extraParams}).on("autocompleteshow",function(){var resultsPane=$(".ui-autocomplete-results:not("+":has(.ui-autocomplete-footer))");if(resultsPane.length>0){$("<div/>").addClass("ui-autocomplete-footer").text("Press Tab to auto-complete.").appendTo(resultsPane);}});});};function publishDraft(){if($.trim($("#target_groups").html())==""&&$.trim($("#target_people").html())==""){alert("There must be at least one reviewer or group "+"before this review request can be published.");}else if($.trim($("#summary").html())==""){alert("The draft must have a summary.");}else if($.trim($("#description").html())==""){alert("The draft must have a description.");}else{gReviewRequest.publish({buttons:gDraftBannerButtons});}}
$.fn.commentSection=function(review_id,context_id,context_type){var self=$(this);var review=gReviewRequest.createReview(review_id);var review_reply=review.createReply();var sectionId=context_id;var reviewEl=$("#review"+review_id);var commentsList=$(".reply-comments",self)
var bannersEl=$(".banners",reviewEl);var bannerButtonsEl=$("input",bannersEl)
var addCommentLink=$(".add_comment_link",self).click(function(){createNewCommentForm();return false;});var yourcomments=$("pre[id^=yourcomment_]",self);if(yourcomments.length>0){createCommentEditor(yourcomments);showReplyDraftBanner(review_id);addCommentLink.hide();}
function createNewCommentForm(){var yourcomment_id="yourcomment_"+review_id+"_"+
context_type;if(sectionId){yourcomment_id+="_"+sectionId;}
yourcomment_id+="-draft";var yourcomment=$("<li/>").addClass("reply-comment draft editor").attr("id",yourcomment_id+"-item").append($("<dl/>").append($("<dt/>").append($("<label/>").attr("for",yourcomment_id).append($("<a/>").attr("href",gUserURL).html(gUserFullName))).append('<dd><pre id="'+yourcomment_id+'"/></dd>'))).appendTo(commentsList);var yourcommentEl=$("#"+yourcomment_id);createCommentEditor(yourcommentEl);yourcommentEl.inlineEditor("startEdit").on("cancel",function(el,initialValue){if(initialValue==""){yourcomment.remove();}});addCommentLink.hide();}
function createCommentEditor(els){return els.each(function(){var self=$(this);self.inlineEditor({cls:"inline-comment-editor",editIconPath:STATIC_URLS["rb/images/edit.png"],notifyUnchangedCompletion:true,multiline:true}).on({"beginEdit":function(){gEditCount++;},"complete":function(e,value){gEditCount--;self.html(linkifyText(self.text()));if(context_type=="body_top"||context_type=="body_bottom"){review_reply[context_type]=value;obj=review_reply;}else if(context_type==="diff_comments"){obj=new RB.DiffCommentReply(review_reply,null,context_id);obj.setText(value);}else if(context_type==="screenshot_comments"){obj=new RB.ScreenshotCommentReply(review_reply,null,context_id);obj.setText(value);}else if(context_type==="file_attachment_comments"){obj=new RB.FileAttachmentCommentReply(review_reply,null,context_id);obj.setText(value);}else{console.log("createCommentEditor received unexpected "+"context type '%s'",context_type);return;}
obj.save({buttons:bannerButtonsEl,success:function(){removeCommentFormIfEmpty(self);showReplyDraftBanner(review_id);}});},"cancel":function(e){gEditCount--;addCommentLink.fadeIn();removeCommentFormIfEmpty(self);}})});}
function removeCommentFormIfEmpty(editorEl){var value=editorEl.inlineEditor("value");if(value.stripTags().strip()!=""){return;}
$("#"+editorEl[0].id+"-item").hide("slow",function(){$(this).remove();if($(".inline-comment-editor",reviewEl).length==0){bannersEl.children().remove();}
addCommentLink.fadeIn();review_reply.discardIfEmpty({buttons:bannerButtonsEl});});}
function showReplyDraftBanner(review_id){if(bannersEl.children().length==0){bannersEl.append($.replyDraftBanner(review_reply,bannerButtonsEl));}}};$.fn.commentIssue=function(review_id,comment_id,comment_type,issue_status,interactive){var self=this;var OPEN='open';var RESOLVED='resolved';var DROPPED='dropped';var issue_reopen_button=$(".issue-button.reopen",this);var issue_resolve_button=$(".issue-button.resolve",this);var issue_drop_button=$(".issue-button.drop",this);self.review_id=review_id;self.comment_id=comment_id;self.comment_type=comment_type;self.issue_status=issue_status;self.interactive=interactive;function disableButtons(){issue_reopen_button.attr("disabled",true);issue_resolve_button.attr("disabled",true);issue_drop_button.attr("disabled",true);}
function enableButtons(){issue_reopen_button.attr("disabled",false);issue_resolve_button.attr("disabled",false);issue_drop_button.attr("disabled",false);}
function enterState(state){disableButtons();gCommentIssueManager.setCommentState(self.review_id,self.comment_id,self.comment_type,state);}
issue_reopen_button.click(function(){enterState(OPEN);});issue_resolve_button.click(function(){enterState(RESOLVED);});issue_drop_button.click(function(){enterState(DROPPED);});self.enter_state=function(state){self.state=self.STATES[state];self.state.enter();if(self.interactive){self.state.showButtons();enableButtons();}}
self.update_issue_summary_table=function(new_status,old_status,timestamp){var comment_id=self.comment_id,entry=$('#summary-table-entry-'+comment_id);issueSummaryTableManager.updateStatus(entry,old_status,new_status);issueSummaryTableManager.updateCounters(old_status,new_status);issueSummaryTableManager.updateTimeStamp(entry,timestamp);}
var open_state={enter:function(){$(".issue-button.reopen",self).hide();$(".issue-state",self).removeClass("dropped").removeClass("resolved").addClass("open");$(".issue-message",self).text("An issue was opened.");},showButtons:function(){$(".issue-button.drop",self).show();$(".issue-button.resolve",self).show();}}
var resolved_state={enter:function(){$(".issue-button.resolve",self).hide();$(".issue-button.drop",self).hide();$(".issue-state",self).removeClass("dropped").removeClass("open").addClass("resolved");$(".issue-message",self).text("The issue has been resolved.");},showButtons:function(){$(".issue-button.reopen",self).show();}}
var dropped_state={enter:function(){$(".issue-button.resolve",self).hide();$(".issue-button.drop",self).hide();$(".issue-state",self).removeClass("open").removeClass("resolved").addClass("dropped");$(".issue-message",self).text("The issue has been dropped.");},showButtons:function(){$(".issue-button.reopen",self).show();}}
self.STATES={};self.STATES[OPEN]=open_state;self.STATES[RESOLVED]=resolved_state;self.STATES[DROPPED]=dropped_state; self.enter_state(self.issue_status); gCommentIssueManager.registerCallback(self.comment_id,self.enter_state); gCommentIssueManager.registerCallback(self.comment_id,self.update_issue_summary_table);return self;}
$.fn.issueIndicator=function(){var issue_indicator=$('<div/>').addClass('issue-state').appendTo(this);var message=$('<span/>').addClass('issue-message').appendTo(issue_indicator);return this;}
$.fn.issueButtons=function(){var issue_indicator=$(".issue-state",this);var buttons=$('<div class="buttons"/>').addClass('buttons').appendTo(issue_indicator);var resolve_string="Fixed";var drop_string="Drop";var reopen_string="Re-open";var button_string='<input type="button" class="issue-button resolve"'
+'value="'+resolve_string+'"/>'
+'<input type="button" class="issue-button drop"'
+'value="'+drop_string+'"/>'
+'<input type="button" class="issue-button reopen"'
+'value="'+reopen_string+'"/>';buttons.append(button_string);return this;}
$.replyDraftBanner=function(review_reply,bannerButtonsEl){var banner=$("<div/>").addClass("banner").append("<h1>This reply is a draft</h1>").append(" Be sure to publish when finished.").append($('<input type="button"/>').val("Publish").click(function(){review_reply.publish({buttons:bannerButtonsEl,success:function(){window.location=gReviewRequestPath;}});})).append($('<input type="button"/>').val("Discard").click(function(){review_reply.discard({buttons:bannerButtonsEl,success:function(){window.location=gReviewRequestPath;}});})).floatReplyDraftBanner();return banner;}
$.fn.floatReplyDraftBanner=function(){return $(this).each(function(){var self=$(this);var floatSpacer=null;var container=null;$(window).scroll(updateFloatPosition).resize(updateSize);_.defer(updateFloatPosition);function updateSize(){if(floatSpacer!=null){self.width(floatSpacer.parent().width()-
self.getExtents("bpm","lr"));}}
function updateFloatPosition(){if(self.parent().length==0){return;}
if($.browser.msie){return;}
if(floatSpacer==null){floatSpacer=self.wrap($("<div/>")).parent();updateSize();}
if(container==null){container=self.closest('.review');}
var containerTop=container.offset().top;var windowTop=$(window).scrollTop();var topOffset=floatSpacer.offset().top-windowTop;var outerHeight=self.outerHeight();if(!container.hasClass("collapsed")&&topOffset<0&&containerTop<windowTop&&windowTop<(containerTop+container.outerHeight()-
outerHeight)){self.addClass('floating').css({top:0,position:"fixed"});updateSize();}else{self.removeClass('floating').css({top:'',position:''});}}});}
$.fn.commentDlg=function(){var DIALOG_TOTAL_HEIGHT=250;var SLIDE_DISTANCE=10;var COMMENTS_BOX_WIDTH=280;var FORM_BOX_WIDTH=380;var self=this;var comment=null;var textFieldWidthDiff=0;var textFieldHeightDiff=0;var dirty=false;var ignoreKeyUp=false;var draftForm=$("#draft-form",this);var commentsPane=$("#review_comments",this);var commentsList=$("#review_comment_list",this);var actionField=$("#comment_action",draftForm);var buttons=$(".buttons",draftForm);var statusField=$(".status",draftForm);var issueOptions=$("#comment-issue-options",draftForm);var issueField=$("#comment_issue",draftForm).click(function(){saveButton.attr("disabled",textField.val()=="");self.setDirty(true);});var cancelButton=$("#comment_cancel",draftForm).click(function(){comment.deleteIfEmpty();self.close();});var deleteButton=$("#comment_delete",this).click(function(){comment.deleteComment();self.close();});var saveButton=$("#comment_save",this).click(function(){comment.setText(textField.val());comment.issue_opened=issueField[0].checked;comment.save();self.close();});var textField=$("#comment_text",draftForm).keydown(function(e){e.stopPropagation();}).keypress(function(e){e.stopPropagation();switch(e.which){case 10:case $.ui.keyCode.ENTER:if(e.ctrlKey){ignoreKeyUp=true;saveButton.click();}
break;case $.ui.keyCode.ESCAPE:ignoreKeyUp=true;cancelButton.click();break;case 73:case 105:if(e.altKey){issueField.click();ignoreKeyUp=true;}
break;default:ignoreKeyUp=false;break;}}).keyup(function(e){if(!ignoreKeyUp){self.setDirty(dirty||comment.text!=textField.val());saveButton.attr("disabled",textField.val()=="");e.stopPropagation();}});this.css("position","absolute").mousedown(function(evt){evt.stopPropagation();}).proxyTouchEvents();if(!$.browser.msie||$.browser.version>=9){var grip=$("<img/>").addClass("ui-resizable-handle ui-resizable-grip").attr("src",STATIC_URLS["rb/images/resize-grip.png"]).insertAfter(buttons).proxyTouchEvents();this.resizable({handles:$.browser.mobileSafari?"grip,se":"grip,n,e,s,w,se,sw,ne,nw",transparent:true,resize:function(){self.handleResize();}});var startOffset=null;var baseWidth=null;var baseHeight=null;$([this[0],textField[0]]).on({"gesturestart":function(evt){startOffset=self.offset();startWidth=self.width();startHeight=self.height();},"gesturechange":function(evt){if(event.scale==0){return false;}
var newWidth=startWidth*event.scale;var newHeight=startHeight*event.scale;self.width(newWidth).height(newHeight).move(startOffset.left-(newWidth-startWidth)/2,startOffset.top-(newHeight-startHeight)/2);self.handleResize();return false;}});grip.css("opacity",100);}
if(!$.browser.msie||$.browser.version>=7){this.draggable({handle:$(".title",this).css("cursor","move")});}
if(!gUserAuthenticated){textField.attr("disabled",true);saveButton.attr("disabled",true);}
this.setDirty=function(newDirty){if(newDirty!=dirty){dirty=newDirty;if(dirty){gEditCount++;statusField.html("This comment has unsaved changes.");}else{gEditCount--;statusField.empty();}
if(this.is(":visible")){this.handleResize();}}
return this;};this.open=function(fromEl){this.css({top:parseInt(this.css("top"),10)-SLIDE_DISTANCE,opacity:0}).show().handleResize().animate({top:"+="+SLIDE_DISTANCE+"px",opacity:1},350,"swing",function(){self.scrollIntoView();}).setDirty(false);cancelButton.attr("disabled",false);deleteButton.attr("disabled",false);saveButton.attr("disabled",textField.val()=="");textField.focus();return this;}
this.close=function(){if(self.is(":visible")){textField.val("");issueField[0].checked=false;cancelButton.attr("disabled",true);deleteButton.attr("disabled",true);saveButton.attr("disabled",true);self.setDirty(false).animate({top:"-="+SLIDE_DISTANCE+"px",opacity:0},350,"swing",function(){self.hide();self.comment=null;self.trigger("close");});}else{self.trigger("close");}
return this;}
this.setCommentsList=function(comments,replyType){commentsList.empty();commentsPane.hide();var showComments=false;if(comments.length>0){var odd=true;$(comments).each(function(i){var item=$("<li/>").addClass(odd?"odd":"even");var header=$("<h2/>").appendTo(item).html(this.user.name);var actions=$('<span class="actions"/>').appendTo(header);$('<a href="'+this.url+'">View</a>').appendTo(actions);$('<a href="'+gReviewRequestPath+'?reply_id='+this.comment_id+'&reply_type='+replyType+'">Reply</a>').appendTo(actions);$("<pre/>").appendTo(item).text(this.text);if(this.issue_opened){var interactive=window['gEditable'];var issue=$('<div/>').issueIndicator();if(interactive){issue.issueButtons();}
issue.commentIssue(this.review_id,this.comment_id,replyType,this.issue_status,interactive).appendTo(item);var self=this;gCommentIssueManager.registerCallback(this.comment_id,function(issue_status){self.issue_status=issue_status;});}
item.appendTo(commentsList);showComments=true;odd=!odd;});}
commentsPane.setVisible(showComments);var width=FORM_BOX_WIDTH;if(showComments){width+=COMMENTS_BOX_WIDTH;}
textField.width(10).height(10);self.width(width).height(DIALOG_TOTAL_HEIGHT);return this;}
this.setDraftComment=function(newComment){if(comment&&comment!=newComment){comment.deleteIfEmpty();}
comment=newComment;comment.ready(function(){textField.val(comment.text);if(comment.loaded){issueField[0].checked=comment.issue_opened;}else{issueField[0].checked=gOpenAnIssue;}
self.setDirty(false);deleteButton.setVisible(comment.loaded);});saveButton.attr("disabled",true);statusField.empty();return this;}
this.handleResize=function(){var width=self.width();var height=self.height();var formWidth=width-draftForm.getExtents("bp","lr");var boxHeight=height;var commentsWidth=0;if(commentsPane.is(":visible")){commentsPane.width(COMMENTS_BOX_WIDTH-commentsPane.getExtents("bp","lr")).height(boxHeight-commentsPane.getExtents("bp","tb")).move(0,0,"absolute");commentsList.height(commentsPane.height()-
commentsList.position().top-
commentsList.getExtents("bmp","b"));commentsWidth=commentsPane.outerWidth(true);formWidth-=commentsWidth;}
draftForm.width(formWidth).height(boxHeight-draftForm.getExtents("bp","tb")).move(commentsWidth,0,"absolute");var textFieldPos=textField.position();textField.width(draftForm.width()-textFieldPos.left-
textField.getExtents("bmp","r")).height(draftForm.height()-textFieldPos.top-
buttons.outerHeight(true)-
statusField.height()-
issueOptions.height()-
textField.getExtents("bmp","b"));return this;}
return this;};$.reviewForm=function(review){RB.apiCall({type:"GET",dataType:"html",data:{},url:gReviewRequestPath+"reviews/draft/inline-form/",success:function(html){createForm(html);}});var dlg;var buttons;function createForm(formHTML){gEditCount++;dlg=$("<div/>").attr("id","review-form").appendTo("body")
.html(formHTML).modalBox({title:"Review for: "+gReviewRequestSummary,stretchX:true,stretchY:true,buttons:[$('<input type="button"/>').val("Publish Review").click(function(e){saveReview(true);return false;}),$('<input type="button"/>').val("Discard Review").click(function(e){gEditCount--;review.deleteReview({buttons:buttons});}),$('<input type="button"/>').val("Cancel").click(function(){gEditCount--;}),$('<input type="button"/>').val("Save").click(function(){saveReview();return false;})]}).keypress(function(e){e.stopPropagation();}).trigger("ready");buttons=$("input",dlg);var body_classes=["body-top","body-bottom"];for(var i in body_classes){var cls=body_classes[i];$("."+cls,dlg).inlineEditor({cls:cls+"-editor",extraHeight:50,forceOpen:true,multiline:true,notifyUnchangedCompletion:true,showButtons:false,showEditIcon:false}).on({"beginEdit":function(){gEditCount++;},"cancel complete":function(){gEditCount--;}});}
$("textarea:first",dlg).focus();dlg.attr("scrollTop",0);loadDiffFragments("review_draft_diff_comments","review_draft_comment_container");}
function saveReview(publish){$.funcQueue("reviewForm").clear();$(".body-top, .body-bottom").inlineEditor("save");$(".comment-editable",dlg).each(function(){var editable=$(this);var comment=editable.data('comment');var issue=editable.next()[0];var issueOpened=issue?issue.checked:false;if(editable.inlineEditor("dirty")||issueOpened!=comment.issue_opened){comment.issue_opened=issueOpened;$.funcQueue("reviewForm").add(function(){editable.one("saved",$.funcQueue("reviewForm").next).inlineEditor("save");});}});$.funcQueue("reviewForm").add(function(){review.ship_it=$("#id_shipit",dlg)[0].checked;review.body_top=$(".body-top",dlg).text();;review.body_bottom=$(".body-bottom",dlg).text();;var options={buttons:buttons,success:$.funcQueue("reviewForm").next};gEditCount--;if(publish){review.publish(options);}
else{review.save(options);}});$.funcQueue("reviewForm").add(function(){dlg.modalBox("destroy");if(publish){hideReviewBanner();gReviewBanner.queue(function(){window.location=gReviewRequestPath;});}else{showReviewBanner();}});$.funcQueue("reviewForm").start();}};$.fn.reviewFormCommentEditor=function(comment){var self=this;return this.inlineEditor({extraHeight:50,forceOpen:true,multiline:true,notifyUnchangedCompletion:true,showButtons:false,showEditIcon:false,useEditIconOnly:false}).on({"beginEdit":function(){gEditCount++;},"cancel":function(){gEditCount--;},"complete":function(e,value){gEditCount--;comment.text=value;comment.save({success:function(){self.trigger("saved");}});}}).data('comment',comment);};$.fn.reviewCloseCommentEditor=function(type){return this.inlineEditor({editIconPath:STATIC_URLS["rb/images/edit.png"],multiline:true,startOpen:false}).on("complete",function(e,value){gReviewRequest.close({type:type,description:value});});}
$.fn.reviewRequestFieldEditor=function(){return this.each(function(){$(this).inlineEditor({cls:this.id+"-editor",editIconPath:STATIC_URLS["rb/images/edit.png"],multiline:this.tagName=="PRE",showButtons:!$(this).hasClass("screenshot-editable"),startOpen:this.id=="changedescription",useEditIconOnly:$(this).hasClass("comma-editable"),showRequiredFlag:$(this).hasClass("required")}).on({"beginEdit":function(){gEditCount++;},"cancel":function(){gEditCount--;},"complete":function(e,value){gEditCount--;setDraftField(this.id,value);}});});}
$.fn.screenshotThumbnail=function(){return $(this).each(function(){var self=$(this);var screenshot_id=self.attr("data-screenshot-id");var screenshot=gReviewRequest.createScreenshot(screenshot_id);var captionEl=self.find(".screenshot-caption");captionEl.find("a.edit").inlineEditor({cls:this.id+"-editor",editIconPath:STATIC_URLS["rb/images/edit.png"],showButtons:false}).on({"beginEdit":function(){gEditCount++;},"cancel":function(){gEditCount--;},"complete":function(e,value){gEditCount--;screenshot.ready(function(){screenshot.caption=value;screenshot.save({buttons:gDraftBannerButtons,success:function(rsp){gDraftBanner.show();}});});}});captionEl.find("a.delete").click(function(){screenshot.ready(function(){screenshot.deleteScreenshot()
self.empty();gDraftBanner.show();});return false;});});}
$.fn.fileAttachment=function(){return $(this).each(function(){var self=$(this);var fileID=self.attr("data-file-id");var fileAttachment=gReviewRequest.createFileAttachment(fileID);var draftComment=null;var comments=[];var commentsProcessed=false;self.find("a.edit").inlineEditor({cls:"file-"+fileID+"-editor",editIconPath:STATIC_URLS["rb/images/edit.png"],showButtons:false}).on({"beginEdit":function(){if($(this).hasClass("empty-caption")){$(this).inlineEditor("field").val("");}
gEditCount++;},"cancel":function(){gEditCount--;},"complete":function(e,value){gEditCount--;if(value===""){$(this).text("No caption").addClass("empty-caption");}else{$(this).removeClass("empty-caption");}
fileAttachment.ready(function(){fileAttachment.caption=value;fileAttachment.save({buttons:gDraftBannerButtons,success:function(rsp){gDraftBanner.show();}});});}});var addCommentButton=self.find('.file-add-comment a').click(function(){showCommentDlg();return false;});self.find('.file-review-inline a').click(function(){showReviewUI();return false;});self.find("a.delete").click(function(){fileAttachment.ready(function(){fileAttachment.deleteFileAttachment()
self.empty();gDraftBanner.show();});return false;});function showCommentDlg(){gCommentDlg.one("close",function(){processComments();createDraftComment();gCommentDlg.setDraftComment(draftComment).setCommentsList(comments,"file_attachment_comments").positionToSide(addCommentButton,{side:'b',fitOnScreen:true});gCommentDlg.open();}).close();}
function showReviewUI(){}
function processComments(){if(commentsProcessed){return;}
var attachmentComments=gFileAttachmentComments[fileID];if(attachmentComments&&attachmentComments.length>0){for(var i in attachmentComments){var comment=attachmentComments[i];if(comment.localdraft){createDraftComment(comment.comment_id,comment.text);}else{comments.push(comment);}}}
commentsProcessed=true;}
function createDraftComment(commentID,text){if(draftComment!=null){return;}
var self=this;var review=gReviewRequest.createReview();draftComment=review.createFileAttachmentComment(commentID,fileID);if(text){draftComment.text=text;}
$.event.add(draftComment,"saved",function(){showReviewBanner();});}});}
var newFileAttachmentPlaceholderTemplate=_.template(['<div class="file-container">',' <div class="file">','  <div class="file-header" />','  <div class="file-thumbnail-container">','   <img class="file-thumbnail" width="16" height="16" src="<%= spinner %>" />','  </div>','  <div class="file-caption" />',' </div>','</div>'].join(''));$.newFileAttachmentPlaceholder=function(){var attachments=$("#file-list");var container=$(newFileAttachmentPlaceholderTemplate({spinner:STATIC_URLS['rb/images/spinner.gif']}));$(attachments.parent()[0]).show();return container.insertBefore(attachments.children("br"));}
var newFileAttachmentTemplate=_.template(['<div class="file-container" data-file-id="<%= id %>">',' <div class="file">','  <ul class="actions">','   <% if (review_url) { %>','    <li class="file-review"><a href="<%= review_url %>">Review</a></li>','   <% } else { %>','    <li class="file-add-comment"><a href="#">Add Comment</a></li>','   <% } %>','  </ul>','  <div class="file-header">','   <a href="<%= url %>">','    <img src="<%= icon_url %>" />','    <%= filename %>','   </a>','   <a href="#" class="delete">','    <img src="<%= delete_image_url %>" alt="Delete File" />','   </a>','  </div>','  <div class="file-thumbnail-container">','   <% if (review_url) { %><a href="<%= review_url %>"><% } %>','   <%= thumbnail %>','   <% if (review_url) { %></a><% } %>','  </div>','  <div class="file-caption">','   <a href="<%= url %>" class="edit <% if (!caption) { %>empty-caption<% } %>">','    <% if (caption) { %><%= caption %><% } else { %>No caption<% } %>','   </a>','  </div>',' </div>','</div>'].join(''));$.newFileAttachment=function(fileAttachment){var container,attachments=$("#file-list");container=$(newFileAttachmentTemplate({caption:fileAttachment.caption,delete_image_url:STATIC_URLS['rb/images/delete.png'],filename:fileAttachment.filename,icon_url:fileAttachment.icon_url,id:fileAttachment.id,review_url:fileAttachment.review_url,thumbnail:fileAttachment.thumbnail,url:fileAttachment.url}));container.fileAttachment();$(attachments.parent()[0]).show();return container.insertBefore(attachments.children("br"));};RB.setFileAttachmentComments=function(comments){gFileAttachmentComments=comments;}
RB.registerForUpdates=function(lastTimestamp,type){function updateFavIcon(url){var head=$("head");head.find("link[rel=icon]").remove();head.append($("<link/>").attr({href:url,rel:"icon",type:"image/x-icon"}));}
var bubble=$("#updates-bubble");var summaryEl;var userEl;var faviconEl=$("head").find("link[rel=icon]");var faviconURL=faviconEl.attr("href");var faviconNotifyURL=STATIC_URLS["rb/images/favicon_notify.ico"];$.event.add(gReviewRequest,"updated",function(evt,info){if(bubble.length==0){updateFavIcon(faviconNotifyURL);bubble=$('<div id="updates-bubble"/>');summaryEl=$('<span/>').appendTo(bubble);bubble.append(" by ");userEl=$('<a href="" id="updates-bubble-user"/>').appendTo(bubble);bubble.append($('<span id="updates-bubble-buttons"/>').append($('<a href="#">Update Page</a>').click(function(){window.location=gReviewRequestPath;return false;})).append(" | ").append($('<a href="#">Ignore</a>').click(function(){bubble.fadeOut();updateFavIcon(faviconURL);return false;}))).appendTo(document.body);}
summaryEl.text(info.summary);userEl.attr('href',info.user.url).text(info.user.fullname);bubble.hide().css("position",$.browser.msie&&$.browser.version==6?"absolute":"fixed").fadeIn();});gReviewRequest.beginCheckForUpdates(type,lastTimestamp);}
function showReviewBanner(){if(gReviewBanner.is(":hidden")){gReviewBanner.slideDown().find(".banner").hide().slideDown();}}
function hideReviewBanner(){gReviewBanner.slideUp().find(".banner").slideUp();}
RB.queueLoadDiffFragment=function(queue_name,comment_id,key){if(!gPendingDiffFragments[queue_name]){gPendingDiffFragments[queue_name]={};}
if(!gPendingDiffFragments[queue_name][key]){gPendingDiffFragments[queue_name][key]=[];}
gPendingDiffFragments[queue_name][key].push(comment_id);}
function loadDiffFragments(queue_name,container_prefix){if(!gPendingDiffFragments[queue_name]){return;}
for(var key in gPendingDiffFragments[queue_name]){var comments=gPendingDiffFragments[queue_name][key];var url=gReviewRequestPath+"fragments/diff-comments/";for(var i=0;i<comments.length;i++){url+=comments[i];if(i!=comments.length-1){url+=","}}
url+="/?queue="+queue_name+"&container_prefix="+container_prefix+"&"+AJAX_SERIAL;$.funcQueue("diff_comments").add(function(url){var e=document.createElement("script");e.type="text/javascript";e.src=url;document.body.appendChild(e);}(url));}
gPendingDiffFragments[queue_name]={};$.funcQueue(queue_name).start();}
function initDnD(){var dropIndicator=null;var fileDropBox;var middleBox;var removeDropIndicatorHandle=null;$(document.body).on("dragenter",function(event){handleDragEnter(event);});function handleDragEnter(event){if(!dropIndicator){var height=$(window).height();dropIndicator=$("<div/>").addClass("drop-indicator").appendTo(document.body).width($(window).width()).height(height).on("dragleave",function(event){if(event.pageX<=0||event.pageX>=dropIndicator.width()){handleDragExit();}
return false;}).mouseenter(function(){handleDragExit();return false;});fileDropBox=$("<div/>").addClass("dropbox").appendTo(dropIndicator).on('drop',handleDrop)
var fileText=$("<h1/>").text("Drop to Upload").appendTo(fileDropBox);fileDropBox.height(height).on({"dragover":function(){var dt=event.originalEvent.dataTransfer;if(dt){dt.dropEffect="copy";}
$(this).addClass("hover");return false;},"dragleave":function(event){var dt=event.originalEvent.dataTransfer;if(dt){dt.dropEffect="none";}
$(this).removeClass("hover");}});fileText.css("margin-top",-fileText.height()/2);}}
function handleDragExit(closeImmediately){if(dropIndicator==null){return;}
if(removeDropIndicatorHandle){window.clearInterval(removeDropIndicatorHandle);removeDropIndicatorHandle=null;}
if(closeImmediately){dropIndicator.fadeOut(function(){dropIndicator.remove();dropIndicator=null;});}else{removeDropIndicatorHandle=window.setInterval(function(){handleDragExit(true);},1000);}}
function handleDrop(event){event.stopPropagation();event.preventDefault();var dt=event.originalEvent.dataTransfer;var files=dt&&dt.files;if(!files){return;}
for(var i=0;i<files.length;i++){uploadFile(files[i]);}
handleDragExit(true);}
function uploadFile(file){var thumb=$.newFileAttachmentPlaceholder().css("opacity",0).fadeTo(1000,1);var fileAttachment=gReviewRequest.createFileAttachment();fileAttachment.setFile(file);fileAttachment.save({buttons:gDraftBannerButtons,success:function(rsp,fileAttachment){thumb.replaceWith($.newFileAttachment(fileAttachment));gDraftBanner.show();},error:function(rsp,msg){thumb.remove();}});}}
$(document).ready(function(){var menuitem=null;function showMenu(){if(menuitem){$("ul",menuitem).fadeOut("fast");menuitem=null;}
$("ul",this).fadeIn("fast");}
function hideMenu(){menuitem=$(this);setTimeout(function(){if(menuitem){$("ul",menuitem).fadeOut("fast");}},400);}
$(".actions > li:has(ul.menu)").hover(showMenu,hideMenu).toggle(showMenu,hideMenu);$("#btn-draft-publish").click(function(){gPublishing=true;var fields=$(".editable:inlineEditorDirty");gPendingSaveCount=fields.length;if(gPendingSaveCount==0){publishDraft();}else{fields.inlineEditor("save");}
return false;});$("#btn-draft-discard").click(function(){gReviewRequest.discardDraft({options:gDraftBannerButtons});return false;});$("#btn-review-request-discard, #discard-review-request-link").click(function(){gReviewRequest.close({type:RB.ReviewRequest.CLOSE_DISCARDED,buttons:gDraftBannerButtons});return false;});$("#link-review-request-close-submitted").click(function(){var submit=true;if($("#draft-banner").is(":visible")){submit=confirm("You have an unpublished draft. If you close "+"this review request, the draft will be "+"discarded. Are you sure you want to close "+"the review request?");}
if(submit){gReviewRequest.close({type:RB.ReviewRequest.CLOSE_SUBMITTED,buttons:gDraftBannerButtons});}
return false;});$("#btn-review-request-reopen").click(function(){gReviewRequest.reopen({buttons:gDraftBannerButtons});return false;});$("#delete-review-request-link").click(function(){var dlg=$("<p/>").text("This deletion cannot be undone. All diffs and reviews "+"will be deleted as well.").modalBox({title:"Are you sure you want to delete this review request?",buttons:[$('<input type="button" value="Cancel"/>'),$('<input type="button" value="Delete"/>').click(function(e){gReviewRequest.deletePermanently({buttons:gDraftBannerButtons.add($("input",dlg.modalBox("buttons"))),success:function(){window.location=SITE_ROOT;}});})]});return false;});var pendingReview=gReviewRequest.createReview();$("#review-link, #review-banner-edit").click(function(){$.reviewForm(pendingReview);});$("#shipit-link").click(function(){if(confirm("Are you sure you want to post this review?")){pendingReview.ship_it=true;pendingReview.body_top="Ship It!";pendingReview.publish({buttons:null,success:function(){hideReviewBanner();gReviewBanner.queue(function(){window.location=gReviewRequestPath;});}});}});$("#review-banner-publish").click(function(){pendingReview.publish({buttons:$("input",gReviewBanner),success:function(){hideReviewBanner();gReviewBanner.queue(function(){window.location=gReviewRequestPath;});}});});$("#review-banner-discard").click(function(){var dlg=$("<p/>").text("If you discard this review, all related comments will "+"be permanently deleted.").modalBox({title:"Are you sure you want to discard this review?",buttons:[$('<input type="button" value="Cancel"/>'),$('<input type="button" value="Discard"/>').click(function(e){pendingReview.deleteReview({buttons:$("input",gReviewBanner),success:function(){hideReviewBanner();gReviewBanner.queue(function(){window.location=gReviewRequestPath;});}});})]});});$("pre.reviewtext, #description, #testing_done").each(function(){$(this).html(linkifyText($(this).text()));});$(".collapse-button").click(function(){$(this).closest(".box").toggleClass('collapsed');});$("#expand-all").click(function(){$(".collapsed").removeClass("collapsed");return false;});$("#collapse-all").click(function(){$(".box").addClass("collapsed");return false;});gCommentDlg=$("#comment-detail").commentDlg().css("z-index",999);gCommentDlg.appendTo("body");$("#submitted-banner #changedescription.editable").reviewCloseCommentEditor(RB.ReviewRequest.CLOSE_SUBMITTED);$("#discard-banner #changedescription.editable").reviewCloseCommentEditor(RB.ReviewRequest.CLOSE_DISCARDED);if(gUserAuthenticated){if(window["gEditable"]){$(".editable").reviewRequestFieldEditor();$(".screenshot-container").screenshotThumbnail();$(".file-container").fileAttachment();var targetGroupsEl=$("#target_groups");var targetPeopleEl=$("#target_people");if(targetGroupsEl.length>0){targetGroupsEl.inlineEditor("field").on({"beginEdit":function(){gEditCount++;},"cancel complete":function(){gEditCount--;}}).reviewsAutoComplete({fieldName:"groups",nameKey:"name",descKey:"display_name",extraParams:{displayname:1}});}
if(targetPeopleEl.length>0){targetPeopleEl.inlineEditor("field").on({"beginEdit":function(){gEditCount++;},"cancel complete":function(){gEditCount--;}}).reviewsAutoComplete({fieldName:"users",nameKey:"username",descKey:"fullname",extraParams:{fullname:1}});}
window.onbeforeunload=function(evt){if(gEditCount>0){var msg="You have unsaved changes that will "+"be lost if you navigate away from "+"this page.";evt=evt||window.event;evt.returnValue=msg;return msg;}};initDnD();}}
loadDiffFragments("diff_fragments","comment_container");issueSummaryTableManager=new RB.IssueSummaryTableView({el:$('#issue-summary'),model:gCommentIssueManager});issueSummaryTableManager.render();});}).call(this);