##// END OF EJS Templates
rhodecode.js: remove unused stuff
Mads Kiilerich -
r4157:bc296381 rhodecode-2.2.5-gpl
parent child Browse files
Show More
@@ -1,2517 +1,2348
1 /**
1 /**
2 RhodeCode JS Files
2 RhodeCode JS Files
3 **/
3 **/
4
4
5 if (typeof console == "undefined" || typeof console.log == "undefined"){
5 if (typeof console == "undefined" || typeof console.log == "undefined"){
6 console = { log: function() {} }
6 console = { log: function() {} }
7 }
7 }
8
8
9
10 var str_repeat = function(i, m) {
11 for (var o = []; m > 0; o[--m] = i);
12 return o.join('');
13 };
14
15 /**
9 /**
16 * INJECT .format function into String
10 * INJECT .format function into String
17 * Usage: "My name is {0} {1}".format("Johny","Bravo")
11 * Usage: "My name is {0} {1}".format("Johny","Bravo")
18 * Return "My name is Johny Bravo"
12 * Return "My name is Johny Bravo"
19 * Inspired by https://gist.github.com/1049426
13 * Inspired by https://gist.github.com/1049426
20 */
14 */
21 String.prototype.format = function() {
15 String.prototype.format = function() {
22
23 function format() {
16 function format() {
24 var str = this;
17 var str = this;
25 var len = arguments.length+1;
18 var len = arguments.length+1;
26 var safe = undefined;
19 var safe = undefined;
27 var arg = undefined;
20 var arg = undefined;
28
21
29 // For each {0} {1} {n...} replace with the argument in that position. If
22 // For each {0} {1} {n...} replace with the argument in that position. If
30 // the argument is an object or an array it will be stringified to JSON.
23 // the argument is an object or an array it will be stringified to JSON.
31 for (var i=0; i < len; arg = arguments[i++]) {
24 for (var i=0; i < len; arg = arguments[i++]) {
32 safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
25 safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
33 str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
26 str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
34 }
27 }
35 return str;
28 return str;
36 }
29 }
37
30
38 // Save a reference of what may already exist under the property native.
31 // Save a reference of what may already exist under the property native.
39 // Allows for doing something like: if("".format.native) { /* use native */ }
32 // Allows for doing something like: if("".format.native) { /* use native */ }
40 format.native = String.prototype.format;
33 format.native = String.prototype.format;
41
34
42 // Replace the prototype property
35 // Replace the prototype property
43 return format;
36 return format;
44
37
45 }();
38 }();
46
39
47 String.prototype.strip = function(char) {
40 String.prototype.strip = function(char) {
48 if(char === undefined){
41 if(char === undefined){
49 char = '\\s';
42 char = '\\s';
50 }
43 }
51 return this.replace(new RegExp('^'+char+'+|'+char+'+$','g'), '');
44 return this.replace(new RegExp('^'+char+'+|'+char+'+$','g'), '');
52 }
45 }
46
53 String.prototype.lstrip = function(char) {
47 String.prototype.lstrip = function(char) {
54 if(char === undefined){
48 if(char === undefined){
55 char = '\\s';
49 char = '\\s';
56 }
50 }
57 return this.replace(new RegExp('^'+char+'+'),'');
51 return this.replace(new RegExp('^'+char+'+'),'');
58 }
52 }
53
59 String.prototype.rstrip = function(char) {
54 String.prototype.rstrip = function(char) {
60 if(char === undefined){
55 if(char === undefined){
61 char = '\\s';
56 char = '\\s';
62 }
57 }
63 return this.replace(new RegExp(''+char+'+$'),'');
58 return this.replace(new RegExp(''+char+'+$'),'');
64 }
59 }
65
60
66
61
67 if(!Array.prototype.indexOf) {
62 if(!Array.prototype.indexOf) {
68 Array.prototype.indexOf = function(needle) {
63 Array.prototype.indexOf = function(needle) {
69 for(var i = 0; i < this.length; i++) {
64 for(var i = 0; i < this.length; i++) {
70 if(this[i] === needle) {
65 if(this[i] === needle) {
71 return i;
66 return i;
72 }
67 }
73 }
68 }
74 return -1;
69 return -1;
75 };
70 };
76 }
71 }
77
72
78 // IE(CRAP) doesn't support previousElementSibling
73 // IE(CRAP) doesn't support previousElementSibling
79 var prevElementSibling = function( el ) {
74 var prevElementSibling = function( el ) {
80 if( el.previousElementSibling ) {
75 if( el.previousElementSibling ) {
81 return el.previousElementSibling;
76 return el.previousElementSibling;
82 } else {
77 } else {
83 while( el = el.previousSibling ) {
78 while( el = el.previousSibling ) {
84 if( el.nodeType === 1 ) return el;
79 if( el.nodeType === 1 ) return el;
85 }
80 }
86 }
81 }
87 }
82 }
88
83
89 /**
84 /**
90 * SmartColorGenerator
91 *
92 *usage::
93 * var CG = new ColorGenerator();
94 * var col = CG.getColor(key); //returns array of RGB
95 * 'rgb({0})'.format(col.join(',')
96 *
97 * @returns {ColorGenerator}
98 */
99 var ColorGenerator = function(){
100 this.GOLDEN_RATIO = 0.618033988749895;
101 this.CURRENT_RATIO = 0.22717784590367374 // this can be random
102 this.HSV_1 = 0.75;//saturation
103 this.HSV_2 = 0.95;
104 this.color;
105 this.cacheColorMap = {};
106 };
107
108 ColorGenerator.prototype = {
109 getColor:function(key){
110 if(this.cacheColorMap[key] !== undefined){
111 return this.cacheColorMap[key];
112 }
113 else{
114 this.cacheColorMap[key] = this.generateColor();
115 return this.cacheColorMap[key];
116 }
117 },
118 _hsvToRgb:function(h,s,v){
119 if (s == 0.0)
120 return [v, v, v];
121 i = parseInt(h * 6.0)
122 f = (h * 6.0) - i
123 p = v * (1.0 - s)
124 q = v * (1.0 - s * f)
125 t = v * (1.0 - s * (1.0 - f))
126 i = i % 6
127 if (i == 0)
128 return [v, t, p]
129 if (i == 1)
130 return [q, v, p]
131 if (i == 2)
132 return [p, v, t]
133 if (i == 3)
134 return [p, q, v]
135 if (i == 4)
136 return [t, p, v]
137 if (i == 5)
138 return [v, p, q]
139 },
140 generateColor:function(){
141 this.CURRENT_RATIO = this.CURRENT_RATIO+this.GOLDEN_RATIO;
142 this.CURRENT_RATIO = this.CURRENT_RATIO %= 1;
143 HSV_tuple = [this.CURRENT_RATIO, this.HSV_1, this.HSV_2]
144 RGB_tuple = this._hsvToRgb(HSV_tuple[0],HSV_tuple[1],HSV_tuple[2]);
145 function toRgb(v){
146 return ""+parseInt(v*256)
147 }
148 return [toRgb(RGB_tuple[0]),toRgb(RGB_tuple[1]),toRgb(RGB_tuple[2])];
149
150 }
151 }
152
153 /**
154 * A customized version of PyRoutes.JS from https://pypi.python.org/pypi/pyroutes.js/
85 * A customized version of PyRoutes.JS from https://pypi.python.org/pypi/pyroutes.js/
155 * which is copyright Stephane Klein and was made available under the BSD License.
86 * which is copyright Stephane Klein and was made available under the BSD License.
156 *
87 *
157 * Usage pyroutes.url('mark_error_fixed',{"error_id":error_id}) // /mark_error_fixed/<error_id>
88 * Usage pyroutes.url('mark_error_fixed',{"error_id":error_id}) // /mark_error_fixed/<error_id>
158 */
89 */
159 var pyroutes = (function() {
90 var pyroutes = (function() {
160 // access global map defined in special file pyroutes
91 // access global map defined in special file pyroutes
161 var matchlist = PROUTES_MAP;
92 var matchlist = PROUTES_MAP;
162 var sprintf = (function() {
93 var sprintf = (function() {
163 function get_type(variable) {
94 function get_type(variable) {
164 return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
95 return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
165 }
96 }
166 function str_repeat(input, multiplier) {
97 function str_repeat(input, multiplier) {
167 for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
98 for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
168 return output.join('');
99 return output.join('');
169 }
100 }
170
101
171 var str_format = function() {
102 var str_format = function() {
172 if (!str_format.cache.hasOwnProperty(arguments[0])) {
103 if (!str_format.cache.hasOwnProperty(arguments[0])) {
173 str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
104 str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
174 }
105 }
175 return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
106 return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
176 };
107 };
177
108
178 str_format.format = function(parse_tree, argv) {
109 str_format.format = function(parse_tree, argv) {
179 var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
110 var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
180 for (i = 0; i < tree_length; i++) {
111 for (i = 0; i < tree_length; i++) {
181 node_type = get_type(parse_tree[i]);
112 node_type = get_type(parse_tree[i]);
182 if (node_type === 'string') {
113 if (node_type === 'string') {
183 output.push(parse_tree[i]);
114 output.push(parse_tree[i]);
184 }
115 }
185 else if (node_type === 'array') {
116 else if (node_type === 'array') {
186 match = parse_tree[i]; // convenience purposes only
117 match = parse_tree[i]; // convenience purposes only
187 if (match[2]) { // keyword argument
118 if (match[2]) { // keyword argument
188 arg = argv[cursor];
119 arg = argv[cursor];
189 for (k = 0; k < match[2].length; k++) {
120 for (k = 0; k < match[2].length; k++) {
190 if (!arg.hasOwnProperty(match[2][k])) {
121 if (!arg.hasOwnProperty(match[2][k])) {
191 throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
122 throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
192 }
123 }
193 arg = arg[match[2][k]];
124 arg = arg[match[2][k]];
194 }
125 }
195 }
126 }
196 else if (match[1]) { // positional argument (explicit)
127 else if (match[1]) { // positional argument (explicit)
197 arg = argv[match[1]];
128 arg = argv[match[1]];
198 }
129 }
199 else { // positional argument (implicit)
130 else { // positional argument (implicit)
200 arg = argv[cursor++];
131 arg = argv[cursor++];
201 }
132 }
202
133
203 if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
134 if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
204 throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
135 throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
205 }
136 }
206 switch (match[8]) {
137 switch (match[8]) {
207 case 'b': arg = arg.toString(2); break;
138 case 'b': arg = arg.toString(2); break;
208 case 'c': arg = String.fromCharCode(arg); break;
139 case 'c': arg = String.fromCharCode(arg); break;
209 case 'd': arg = parseInt(arg, 10); break;
140 case 'd': arg = parseInt(arg, 10); break;
210 case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
141 case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
211 case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
142 case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
212 case 'o': arg = arg.toString(8); break;
143 case 'o': arg = arg.toString(8); break;
213 case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
144 case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
214 case 'u': arg = Math.abs(arg); break;
145 case 'u': arg = Math.abs(arg); break;
215 case 'x': arg = arg.toString(16); break;
146 case 'x': arg = arg.toString(16); break;
216 case 'X': arg = arg.toString(16).toUpperCase(); break;
147 case 'X': arg = arg.toString(16).toUpperCase(); break;
217 }
148 }
218 arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
149 arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
219 pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
150 pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
220 pad_length = match[6] - String(arg).length;
151 pad_length = match[6] - String(arg).length;
221 pad = match[6] ? str_repeat(pad_character, pad_length) : '';
152 pad = match[6] ? str_repeat(pad_character, pad_length) : '';
222 output.push(match[5] ? arg + pad : pad + arg);
153 output.push(match[5] ? arg + pad : pad + arg);
223 }
154 }
224 }
155 }
225 return output.join('');
156 return output.join('');
226 };
157 };
227
158
228 str_format.cache = {};
159 str_format.cache = {};
229
160
230 str_format.parse = function(fmt) {
161 str_format.parse = function(fmt) {
231 var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
162 var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
232 while (_fmt) {
163 while (_fmt) {
233 if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
164 if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
234 parse_tree.push(match[0]);
165 parse_tree.push(match[0]);
235 }
166 }
236 else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
167 else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
237 parse_tree.push('%');
168 parse_tree.push('%');
238 }
169 }
239 else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
170 else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
240 if (match[2]) {
171 if (match[2]) {
241 arg_names |= 1;
172 arg_names |= 1;
242 var field_list = [], replacement_field = match[2], field_match = [];
173 var field_list = [], replacement_field = match[2], field_match = [];
243 if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
174 if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
244 field_list.push(field_match[1]);
175 field_list.push(field_match[1]);
245 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
176 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
246 if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
177 if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
247 field_list.push(field_match[1]);
178 field_list.push(field_match[1]);
248 }
179 }
249 else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
180 else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
250 field_list.push(field_match[1]);
181 field_list.push(field_match[1]);
251 }
182 }
252 else {
183 else {
253 throw('[sprintf] huh?');
184 throw('[sprintf] huh?');
254 }
185 }
255 }
186 }
256 }
187 }
257 else {
188 else {
258 throw('[sprintf] huh?');
189 throw('[sprintf] huh?');
259 }
190 }
260 match[2] = field_list;
191 match[2] = field_list;
261 }
192 }
262 else {
193 else {
263 arg_names |= 2;
194 arg_names |= 2;
264 }
195 }
265 if (arg_names === 3) {
196 if (arg_names === 3) {
266 throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
197 throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
267 }
198 }
268 parse_tree.push(match);
199 parse_tree.push(match);
269 }
200 }
270 else {
201 else {
271 throw('[sprintf] huh?');
202 throw('[sprintf] huh?');
272 }
203 }
273 _fmt = _fmt.substring(match[0].length);
204 _fmt = _fmt.substring(match[0].length);
274 }
205 }
275 return parse_tree;
206 return parse_tree;
276 };
207 };
277
208
278 return str_format;
209 return str_format;
279 })();
210 })();
280
211
281 var vsprintf = function(fmt, argv) {
212 var vsprintf = function(fmt, argv) {
282 argv.unshift(fmt);
213 argv.unshift(fmt);
283 return sprintf.apply(null, argv);
214 return sprintf.apply(null, argv);
284 };
215 };
285 return {
216 return {
286 'url': function(route_name, params) {
217 'url': function(route_name, params) {
287 var result = route_name;
218 var result = route_name;
288 if (typeof(params) != 'object'){
219 if (typeof(params) != 'object'){
289 params = {};
220 params = {};
290 }
221 }
291 if (matchlist.hasOwnProperty(route_name)) {
222 if (matchlist.hasOwnProperty(route_name)) {
292 var route = matchlist[route_name];
223 var route = matchlist[route_name];
293 // param substitution
224 // param substitution
294 for(var i=0; i < route[1].length; i++) {
225 for(var i=0; i < route[1].length; i++) {
295
296 if (!params.hasOwnProperty(route[1][i]))
226 if (!params.hasOwnProperty(route[1][i]))
297 throw new Error(route[1][i] + ' missing in "' + route_name + '" route generation');
227 throw new Error(route[1][i] + ' missing in "' + route_name + '" route generation');
298 }
228 }
299 result = sprintf(route[0], params);
229 result = sprintf(route[0], params);
300
230
301 var ret = [];
231 var ret = [];
302 //extra params => GET
232 //extra params => GET
303 for(param in params){
233 for(param in params){
304 if (route[1].indexOf(param) == -1){
234 if (route[1].indexOf(param) == -1){
305 ret.push(encodeURIComponent(param) + "=" + encodeURIComponent(params[param]));
235 ret.push(encodeURIComponent(param) + "=" + encodeURIComponent(params[param]));
306 }
236 }
307 }
237 }
308 var _parts = ret.join("&");
238 var _parts = ret.join("&");
309 if(_parts){
239 if(_parts){
310 result = result +'?'+ _parts
240 result = result +'?'+ _parts
311 }
241 }
312 }
242 }
313
243
314 return result;
244 return result;
315 },
245 },
316 'register': function(route_name, route_tmpl, req_params) {
246 'register': function(route_name, route_tmpl, req_params) {
317 if (typeof(req_params) != 'object') {
247 if (typeof(req_params) != 'object') {
318 req_params = [];
248 req_params = [];
319 }
249 }
320 //fix escape
250 //fix escape
321 route_tmpl = unescape(route_tmpl);
251 route_tmpl = unescape(route_tmpl);
322 keys = [];
252 keys = [];
323 for (o in req_params){
253 for (o in req_params){
324 keys.push(req_params[o])
254 keys.push(req_params[o])
325 }
255 }
326 matchlist[route_name] = [
256 matchlist[route_name] = [
327 route_tmpl,
257 route_tmpl,
328 keys
258 keys
329 ]
259 ]
330 },
260 },
331 '_routes': function(){
261 '_routes': function(){
332 return matchlist;
262 return matchlist;
333 }
263 }
334 }
264 }
335 })();
265 })();
336
266
337
267
338
339 /**
268 /**
340 * GLOBAL YUI Shortcuts
269 * GLOBAL YUI Shortcuts
341 */
270 */
342 var YUC = YAHOO.util.Connect;
271 var YUC = YAHOO.util.Connect;
343 var YUD = YAHOO.util.Dom;
272 var YUD = YAHOO.util.Dom;
344 var YUE = YAHOO.util.Event;
273 var YUE = YAHOO.util.Event;
345 var YUQ = YAHOO.util.Selector.query;
274 var YUQ = YAHOO.util.Selector.query;
346
275
347 // defines if push state is enabled for this browser ?
348 var push_state_enabled = Boolean(
349 window.history && window.history.pushState && window.history.replaceState
350 && !( /* disable for versions of iOS before version 4.3 (8F190) */
351 (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent)
352 /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
353 || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent)
354 )
355 );
356
357 var _run_callbacks = function(callbacks){
276 var _run_callbacks = function(callbacks){
358 if (callbacks !== undefined){
277 if (callbacks !== undefined){
359 var _l = callbacks.length;
278 var _l = callbacks.length;
360 for (var i=0;i<_l;i++){
279 for (var i=0;i<_l;i++){
361 var func = callbacks[i];
280 var func = callbacks[i];
362 if(typeof(func)=='function'){
281 if(typeof(func)=='function'){
363 try{
282 try{
364 func();
283 func();
365 }catch (err){};
284 }catch (err){};
366 }
285 }
367 }
286 }
368 }
287 }
369 }
288 }
370
289
371 /**
290 /**
372 * turns objects into GET query string
291 * turns objects into GET query string
373 */
292 */
374 var toQueryString = function(o) {
293 var toQueryString = function(o) {
375 if(typeof o !== 'object') {
294 if(typeof o !== 'object') {
376 return false;
295 return false;
377 }
296 }
378 var _p, _qs = [];
297 var _p, _qs = [];
379 for(_p in o) {
298 for(_p in o) {
380 _qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
299 _qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
381 }
300 }
382 return _qs.join('&');
301 return _qs.join('&');
383 };
302 };
384
303
385 /**
304 /**
386 * Partial Ajax Implementation
305 * Partial Ajax Implementation
387 *
306 *
388 * @param url: defines url to make partial request
307 * @param url: defines url to make partial request
389 * @param container: defines id of container to input partial result
308 * @param container: defines id of container to input partial result
390 * @param s_call: success callback function that takes o as arg
309 * @param s_call: success callback function that takes o as arg
391 * o.tId
310 * o.tId
392 * o.status
311 * o.status
393 * o.statusText
312 * o.statusText
394 * o.getResponseHeader[ ]
313 * o.getResponseHeader[ ]
395 * o.getAllResponseHeaders
314 * o.getAllResponseHeaders
396 * o.responseText
315 * o.responseText
397 * o.responseXML
316 * o.responseXML
398 * o.argument
317 * o.argument
399 * @param f_call: failure callback
318 * @param f_call: failure callback
400 * @param args arguments
319 * @param args arguments
401 */
320 */
402 function ypjax(url,container,s_call,f_call,args){
321 function ypjax(url,container,s_call,f_call,args){
403 var method='GET';
322 var method='GET';
404 if(args===undefined){
323 if(args===undefined){
405 args=null;
324 args=null;
406 }
325 }
407
326
408 // Set special header for partial ajax == HTTP_X_PARTIAL_XHR
327 // Set special header for partial ajax == HTTP_X_PARTIAL_XHR
409 YUC.initHeader('X-PARTIAL-XHR',true);
328 YUC.initHeader('X-PARTIAL-XHR',true);
410
329
411 // wrapper of passed callback
330 // wrapper of passed callback
412 var s_wrapper = (function(o){
331 var s_wrapper = (function(o){
413 return function(o){
332 return function(o){
414 YUD.get(container).innerHTML=o.responseText;
333 YUD.get(container).innerHTML=o.responseText;
415 YUD.setStyle(container,'opacity','1.0');
334 YUD.setStyle(container,'opacity','1.0');
416 //execute the given original callback
335 //execute the given original callback
417 if (s_call !== undefined){
336 if (s_call !== undefined){
418 s_call(o);
337 s_call(o);
419 }
338 }
420 }
339 }
421 })()
340 })()
422 YUD.setStyle(container,'opacity','0.3');
341 YUD.setStyle(container,'opacity','0.3');
423 YUC.asyncRequest(method,url,{
342 YUC.asyncRequest(method,url,{
424 success:s_wrapper,
343 success:s_wrapper,
425 failure:function(o){
344 failure:function(o){
426 console.log(o);
345 console.log(o);
427 YUD.get(container).innerHTML='<span class="error_red">ERROR: {0}</span>'.format(o.status);
346 YUD.get(container).innerHTML='<span class="error_red">ERROR: {0}</span>'.format(o.status);
428 YUD.setStyle(container,'opacity','1.0');
347 YUD.setStyle(container,'opacity','1.0');
429 },
348 },
430 cache:false
349 cache:false
431 },args);
350 },args);
432
351
433 };
352 };
434
353
435 var ajaxGET = function(url,success) {
354 var ajaxGET = function(url,success) {
436 // Set special header for ajax == HTTP_X_PARTIAL_XHR
355 // Set special header for ajax == HTTP_X_PARTIAL_XHR
437 YUC.initHeader('X-PARTIAL-XHR',true);
356 YUC.initHeader('X-PARTIAL-XHR',true);
438
357
439 var sUrl = url;
358 var sUrl = url;
440 var callback = {
359 var callback = {
441 success: success,
360 success: success,
442 failure: function (o) {
361 failure: function (o) {
443 if (o.status != 0) {
362 if (o.status != 0) {
444 alert("error: " + o.statusText);
363 alert("error: " + o.statusText);
445 };
364 };
446 },
365 },
447 };
366 };
448
367
449 var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
368 var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
450 return request;
369 return request;
451 };
370 };
452
371
453
454
455 var ajaxPOST = function(url,postData,success) {
372 var ajaxPOST = function(url,postData,success) {
456 // Set special header for ajax == HTTP_X_PARTIAL_XHR
373 // Set special header for ajax == HTTP_X_PARTIAL_XHR
457 YUC.initHeader('X-PARTIAL-XHR',true);
374 YUC.initHeader('X-PARTIAL-XHR',true);
458
375
459 var sUrl = url;
376 var sUrl = url;
460 var callback = {
377 var callback = {
461 success: success,
378 success: success,
462 failure: function (o) {
379 failure: function (o) {
463 alert("error");
380 alert("error");
464 },
381 },
465 };
382 };
466 var postData = toQueryString(postData);
383 var postData = toQueryString(postData);
467 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
384 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
468 return request;
385 return request;
469 };
386 };
470
387
471
388
472 /**
389 /**
473 * tooltip activate
390 * tooltip activate
474 */
391 */
475 var tooltip_activate = function(){
392 var tooltip_activate = function(){
476 yt = YAHOO.yuitip.main;
393 yt = YAHOO.yuitip.main;
477 YUE.onDOMReady(yt.init);
394 YUE.onDOMReady(yt.init);
478 };
395 };
479
396
480 /**
397 /**
481 * show more
398 * show more
482 */
399 */
483 var show_more_event = function(){
400 var show_more_event = function(){
484 YUE.on(YUD.getElementsByClassName('show_more'),'click',function(e){
401 YUE.on(YUD.getElementsByClassName('show_more'),'click',function(e){
485 var el = e.target;
402 var el = e.target;
486 YUD.setStyle(YUD.get(el.id.substring(1)),'display','');
403 YUD.setStyle(YUD.get(el.id.substring(1)),'display','');
487 YUD.setStyle(el.parentNode,'display','none');
404 YUD.setStyle(el.parentNode,'display','none');
488 });
405 });
489 };
406 };
490
407
491 /**
408 /**
492 * show changeset tooltip
409 * show changeset tooltip
493 */
410 */
494 var show_changeset_tooltip = function(){
411 var show_changeset_tooltip = function(){
495 YUE.on(YUD.getElementsByClassName('lazy-cs'), 'mouseover', function(e){
412 YUE.on(YUD.getElementsByClassName('lazy-cs'), 'mouseover', function(e){
496 var target = e.currentTarget;
413 var target = e.currentTarget;
497 var rid = YUD.getAttribute(target,'raw_id');
414 var rid = YUD.getAttribute(target,'raw_id');
498 var repo_name = YUD.getAttribute(target,'repo_name');
415 var repo_name = YUD.getAttribute(target,'repo_name');
499 var ttid = 'tt-'+rid;
416 var ttid = 'tt-'+rid;
500 var success = function(o){
417 var success = function(o){
501 var json = JSON.parse(o.responseText);
418 var json = JSON.parse(o.responseText);
502 YUD.addClass(target,'tooltip')
419 YUD.addClass(target,'tooltip')
503 YUD.setAttribute(target, 'title',json['message']);
420 YUD.setAttribute(target, 'title',json['message']);
504 YAHOO.yuitip.main.show_yuitip(e, target);
421 YAHOO.yuitip.main.show_yuitip(e, target);
505 }
422 }
506 if(rid && !YUD.hasClass(target, 'tooltip')){
423 if(rid && !YUD.hasClass(target, 'tooltip')){
507 YUD.setAttribute(target,'id',ttid);
424 YUD.setAttribute(target,'id',ttid);
508 YUD.setAttribute(target, 'title',_TM['loading ...']);
425 YUD.setAttribute(target, 'title',_TM['loading ...']);
509 YAHOO.yuitip.main.set_listeners(target);
426 YAHOO.yuitip.main.set_listeners(target);
510 YAHOO.yuitip.main.show_yuitip(e, target);
427 YAHOO.yuitip.main.show_yuitip(e, target);
511 var url = pyroutes.url('changeset_info', {"repo_name":repo_name, "revision": rid});
428 var url = pyroutes.url('changeset_info', {"repo_name":repo_name, "revision": rid});
512 ajaxGET(url, success)
429 ajaxGET(url, success)
513 }
430 }
514 });
431 });
515 };
432 };
516
433
517 var onSuccessFollow = function(target){
434 var onSuccessFollow = function(target){
518 var f = YUD.get(target);
435 var f = YUD.get(target);
519 var f_cnt = YUD.get('current_followers_count');
436 var f_cnt = YUD.get('current_followers_count');
520
437
521 if(YUD.hasClass(f, 'follow')){
438 if(YUD.hasClass(f, 'follow')){
522 f.setAttribute('class','following');
439 f.setAttribute('class','following');
523 f.setAttribute('title',_TM['Stop following this repository']);
440 f.setAttribute('title',_TM['Stop following this repository']);
524
441
525 if(f_cnt){
442 if(f_cnt){
526 var cnt = Number(f_cnt.innerHTML)+1;
443 var cnt = Number(f_cnt.innerHTML)+1;
527 f_cnt.innerHTML = cnt;
444 f_cnt.innerHTML = cnt;
528 }
445 }
529 }
446 }
530 else{
447 else{
531 f.setAttribute('class','follow');
448 f.setAttribute('class','follow');
532 f.setAttribute('title',_TM['Start following this repository']);
449 f.setAttribute('title',_TM['Start following this repository']);
533 if(f_cnt){
450 if(f_cnt){
534 var cnt = Number(f_cnt.innerHTML)-1;
451 var cnt = Number(f_cnt.innerHTML)-1;
535 f_cnt.innerHTML = cnt;
452 f_cnt.innerHTML = cnt;
536 }
453 }
537 }
454 }
538 }
455 }
539
456
540 var toggleFollowingUser = function(target,fallows_user_id,token,user_id){
541 args = 'follows_user_id='+fallows_user_id;
542 args+= '&amp;auth_token='+token;
543 if(user_id != undefined){
544 args+="&amp;user_id="+user_id;
545 }
546 YUC.asyncRequest('POST',TOGGLE_FOLLOW_URL,{
547 success:function(o){
548 onSuccessFollow(target);
549 }
550 },args);
551 return false;
552 }
553
554 var toggleFollowingRepo = function(target,fallows_repo_id,token,user_id){
457 var toggleFollowingRepo = function(target,fallows_repo_id,token,user_id){
555
556 args = 'follows_repo_id='+fallows_repo_id;
458 args = 'follows_repo_id='+fallows_repo_id;
557 args+= '&amp;auth_token='+token;
459 args+= '&amp;auth_token='+token;
558 if(user_id != undefined){
460 if(user_id != undefined){
559 args+="&amp;user_id="+user_id;
461 args+="&amp;user_id="+user_id;
560 }
462 }
561 YUC.asyncRequest('POST',TOGGLE_FOLLOW_URL,{
463 YUC.asyncRequest('POST',TOGGLE_FOLLOW_URL,{
562 success:function(o){
464 success:function(o){
563 onSuccessFollow(target);
465 onSuccessFollow(target);
564 }
466 }
565 },args);
467 },args);
566 return false;
468 return false;
567 }
469 }
568
470
569 var showRepoSize = function(target, repo_name, token){
471 var showRepoSize = function(target, repo_name, token){
570 var args= 'auth_token='+token;
472 var args= 'auth_token='+token;
571
473
572 if(!YUD.hasClass(target, 'loaded')){
474 if(!YUD.hasClass(target, 'loaded')){
573 YUD.get(target).innerHTML = _TM['Loading ...'];
475 YUD.get(target).innerHTML = _TM['Loading ...'];
574 var url = pyroutes.url('repo_size', {"repo_name":repo_name});
476 var url = pyroutes.url('repo_size', {"repo_name":repo_name});
575 YUC.asyncRequest('POST',url,{
477 YUC.asyncRequest('POST',url,{
576 success:function(o){
478 success:function(o){
577 YUD.get(target).innerHTML = JSON.parse(o.responseText);
479 YUD.get(target).innerHTML = JSON.parse(o.responseText);
578 YUD.addClass(target, 'loaded');
480 YUD.addClass(target, 'loaded');
579 }
481 }
580 },args);
482 },args);
581 }
483 }
582 return false;
484 return false;
583 }
485 }
584
486
585 /**
487 /**
586 * TOOLTIP IMPL.
488 * TOOLTIP IMPL.
587 */
489 */
588 YAHOO.namespace('yuitip');
490 YAHOO.namespace('yuitip');
589 YAHOO.yuitip.main = {
491 YAHOO.yuitip.main = {
590
492
591 $: YAHOO.util.Dom.get,
493 $: YAHOO.util.Dom.get,
592
494
593 bgColor: '#000',
495 bgColor: '#000',
594 speed: 0.3,
496 speed: 0.3,
595 opacity: 0.9,
497 opacity: 0.9,
596 offset: [15,15],
498 offset: [15,15],
597 useAnim: false,
499 useAnim: false,
598 maxWidth: 600,
500 maxWidth: 600,
599 add_links: false,
501 add_links: false,
600 yuitips: [],
502 yuitips: [],
601
503
602 set_listeners: function(tt){
504 set_listeners: function(tt){
603 YUE.on(tt, 'mouseover', yt.show_yuitip, tt);
505 YUE.on(tt, 'mouseover', yt.show_yuitip, tt);
604 YUE.on(tt, 'mousemove', yt.move_yuitip, tt);
506 YUE.on(tt, 'mousemove', yt.move_yuitip, tt);
605 YUE.on(tt, 'mouseout', yt.close_yuitip, tt);
507 YUE.on(tt, 'mouseout', yt.close_yuitip, tt);
606 },
508 },
607
509
608 init: function(){
510 init: function(){
609 yt.tipBox = yt.$('tip-box');
511 yt.tipBox = yt.$('tip-box');
610 if(!yt.tipBox){
512 if(!yt.tipBox){
611 yt.tipBox = document.createElement('div');
513 yt.tipBox = document.createElement('div');
612 document.body.appendChild(yt.tipBox);
514 document.body.appendChild(yt.tipBox);
613 yt.tipBox.id = 'tip-box';
515 yt.tipBox.id = 'tip-box';
614 }
516 }
615
517
616 YUD.setStyle(yt.tipBox, 'display', 'none');
518 YUD.setStyle(yt.tipBox, 'display', 'none');
617 YUD.setStyle(yt.tipBox, 'position', 'absolute');
519 YUD.setStyle(yt.tipBox, 'position', 'absolute');
618 if(yt.maxWidth !== null){
520 if(yt.maxWidth !== null){
619 YUD.setStyle(yt.tipBox, 'max-width', yt.maxWidth+'px');
521 YUD.setStyle(yt.tipBox, 'max-width', yt.maxWidth+'px');
620 }
522 }
621
523
622 var yuitips = YUD.getElementsByClassName('tooltip');
524 var yuitips = YUD.getElementsByClassName('tooltip');
623
525
624 if(yt.add_links === true){
526 if(yt.add_links === true){
625 var links = document.getElementsByTagName('a');
527 var links = document.getElementsByTagName('a');
626 var linkLen = links.length;
528 var linkLen = links.length;
627 for(i=0;i<linkLen;i++){
529 for(i=0;i<linkLen;i++){
628 yuitips.push(links[i]);
530 yuitips.push(links[i]);
629 }
531 }
630 }
532 }
631
533
632 var yuiLen = yuitips.length;
534 var yuiLen = yuitips.length;
633
535
634 for(i=0;i<yuiLen;i++){
536 for(i=0;i<yuiLen;i++){
635 yt.set_listeners(yuitips[i]);
537 yt.set_listeners(yuitips[i]);
636 }
538 }
637 },
539 },
638
540
639 show_yuitip: function(e, el){
541 show_yuitip: function(e, el){
640 YUE.stopEvent(e);
542 YUE.stopEvent(e);
641 if(el.tagName.toLowerCase() === 'img'){
543 if(el.tagName.toLowerCase() === 'img'){
642 yt.tipText = el.alt ? el.alt : '';
544 yt.tipText = el.alt ? el.alt : '';
643 } else {
545 } else {
644 yt.tipText = el.title ? el.title : '';
546 yt.tipText = el.title ? el.title : '';
645 }
547 }
646
548
647 if(yt.tipText !== ''){
549 if(yt.tipText !== ''){
648 // save org title
550 // save org title
649 YUD.setAttribute(el, 'tt_title', yt.tipText);
551 YUD.setAttribute(el, 'tt_title', yt.tipText);
650 // reset title to not show org tooltips
552 // reset title to not show org tooltips
651 YUD.setAttribute(el, 'title', '');
553 YUD.setAttribute(el, 'title', '');
652
554
653 yt.tipBox.innerHTML = yt.tipText;
555 yt.tipBox.innerHTML = yt.tipText;
654 YUD.setStyle(yt.tipBox, 'display', 'block');
556 YUD.setStyle(yt.tipBox, 'display', 'block');
655 if(yt.useAnim === true){
557 if(yt.useAnim === true){
656 YUD.setStyle(yt.tipBox, 'opacity', '0');
558 YUD.setStyle(yt.tipBox, 'opacity', '0');
657 var newAnim = new YAHOO.util.Anim(yt.tipBox,
559 var newAnim = new YAHOO.util.Anim(yt.tipBox,
658 {
560 {
659 opacity: { to: yt.opacity }
561 opacity: { to: yt.opacity }
660 }, yt.speed, YAHOO.util.Easing.easeOut
562 }, yt.speed, YAHOO.util.Easing.easeOut
661 );
563 );
662 newAnim.animate();
564 newAnim.animate();
663 }
565 }
664 }
566 }
665 },
567 },
666
568
667 move_yuitip: function(e, el){
569 move_yuitip: function(e, el){
668 YUE.stopEvent(e);
570 YUE.stopEvent(e);
669 var movePos = YUE.getXY(e);
571 var movePos = YUE.getXY(e);
670 YUD.setStyle(yt.tipBox, 'top', (movePos[1] + yt.offset[1]) + 'px');
572 YUD.setStyle(yt.tipBox, 'top', (movePos[1] + yt.offset[1]) + 'px');
671 YUD.setStyle(yt.tipBox, 'left', (movePos[0] + yt.offset[0]) + 'px');
573 YUD.setStyle(yt.tipBox, 'left', (movePos[0] + yt.offset[0]) + 'px');
672 },
574 },
673
575
674 close_yuitip: function(e, el){
576 close_yuitip: function(e, el){
675 YUE.stopEvent(e);
577 YUE.stopEvent(e);
676
578
677 if(yt.useAnim === true){
579 if(yt.useAnim === true){
678 var newAnim = new YAHOO.util.Anim(yt.tipBox,
580 var newAnim = new YAHOO.util.Anim(yt.tipBox,
679 {
581 {
680 opacity: { to: 0 }
582 opacity: { to: 0 }
681 }, yt.speed, YAHOO.util.Easing.easeOut
583 }, yt.speed, YAHOO.util.Easing.easeOut
682 );
584 );
683 newAnim.animate();
585 newAnim.animate();
684 } else {
586 } else {
685 YUD.setStyle(yt.tipBox, 'display', 'none');
587 YUD.setStyle(yt.tipBox, 'display', 'none');
686 }
588 }
687 YUD.setAttribute(el,'title', YUD.getAttribute(el, 'tt_title'));
589 YUD.setAttribute(el,'title', YUD.getAttribute(el, 'tt_title'));
688 }
590 }
689 }
591 }
690
592
691 /**
593 /**
692 * Quick filter widget
594 * Quick filter widget
693 *
595 *
694 * @param target: filter input target
596 * @param target: filter input target
695 * @param nodes: list of nodes in html we want to filter.
597 * @param nodes: list of nodes in html we want to filter.
696 * @param display_element function that takes current node from nodes and
598 * @param display_element function that takes current node from nodes and
697 * does hide or show based on the node
599 * does hide or show based on the node
698 *
600 *
699 */
601 */
700 var q_filter = function(target,nodes,display_element){
602 var q_filter = function(target,nodes,display_element){
701
603
702 var nodes = nodes;
604 var nodes = nodes;
703 var q_filter_field = YUD.get(target);
605 var q_filter_field = YUD.get(target);
704 var F = YAHOO.namespace(target);
606 var F = YAHOO.namespace(target);
705
607
706 YUE.on(q_filter_field,'keyup',function(e){
608 YUE.on(q_filter_field,'keyup',function(e){
707 clearTimeout(F.filterTimeout);
609 clearTimeout(F.filterTimeout);
708 F.filterTimeout = setTimeout(F.updateFilter,600);
610 F.filterTimeout = setTimeout(F.updateFilter,600);
709 });
611 });
710
612
711 F.filterTimeout = null;
613 F.filterTimeout = null;
712
614
713 var show_node = function(node){
615 var show_node = function(node){
714 YUD.setStyle(node,'display','')
616 YUD.setStyle(node,'display','')
715 }
617 }
716 var hide_node = function(node){
618 var hide_node = function(node){
717 YUD.setStyle(node,'display','none');
619 YUD.setStyle(node,'display','none');
718 }
620 }
719
621
720 F.updateFilter = function() {
622 F.updateFilter = function() {
721 // Reset timeout
623 // Reset timeout
722 F.filterTimeout = null;
624 F.filterTimeout = null;
723
625
724 var obsolete = [];
626 var obsolete = [];
725
627
726 var req = q_filter_field.value.toLowerCase();
628 var req = q_filter_field.value.toLowerCase();
727
629
728 var l = nodes.length;
630 var l = nodes.length;
729 var i;
631 var i;
730 var showing = 0;
632 var showing = 0;
731
633
732 for (i=0;i<l;i++ ){
634 for (i=0;i<l;i++ ){
733 var n = nodes[i];
635 var n = nodes[i];
734 var target_element = display_element(n)
636 var target_element = display_element(n)
735 if(req && n.innerHTML.toLowerCase().indexOf(req) == -1){
637 if(req && n.innerHTML.toLowerCase().indexOf(req) == -1){
736 hide_node(target_element);
638 hide_node(target_element);
737 }
639 }
738 else{
640 else{
739 show_node(target_element);
641 show_node(target_element);
740 showing+=1;
642 showing+=1;
741 }
643 }
742 }
644 }
743
645
744 // if repo_count is set update the number
646 // if repo_count is set update the number
745 var cnt = YUD.get('repo_count');
647 var cnt = YUD.get('repo_count');
746 if(cnt){
648 if(cnt){
747 YUD.get('repo_count').innerHTML = showing;
649 YUD.get('repo_count').innerHTML = showing;
748 }
650 }
749
750 }
651 }
751 };
652 };
752
653
753 var tableTr = function(cls, body){
654 var tableTr = function(cls, body){
754 var _el = document.createElement('div');
655 var _el = document.createElement('div');
755 var cont = new YAHOO.util.Element(body);
656 var cont = new YAHOO.util.Element(body);
756 var comment_id = fromHTML(body).children[0].id.split('comment-')[1];
657 var comment_id = fromHTML(body).children[0].id.split('comment-')[1];
757 var id = 'comment-tr-{0}'.format(comment_id);
658 var id = 'comment-tr-{0}'.format(comment_id);
758 var _html = ('<table><tbody><tr id="{0}" class="{1}">'+
659 var _html = ('<table><tbody><tr id="{0}" class="{1}">'+
759 '<td class="lineno-inline new-inline"></td>'+
660 '<td class="lineno-inline new-inline"></td>'+
760 '<td class="lineno-inline old-inline"></td>'+
661 '<td class="lineno-inline old-inline"></td>'+
761 '<td>{2}</td>'+
662 '<td>{2}</td>'+
762 '</tr></tbody></table>').format(id, cls, body);
663 '</tr></tbody></table>').format(id, cls, body);
763 _el.innerHTML = _html;
664 _el.innerHTML = _html;
764 return _el.children[0].children[0].children[0];
665 return _el.children[0].children[0].children[0];
765 };
666 };
766
667
767 /** comments **/
768 var removeInlineForm = function(form) {
769 form.parentNode.removeChild(form);
770 };
771
772 var createInlineForm = function(parent_tr, f_path, line) {
668 var createInlineForm = function(parent_tr, f_path, line) {
773 var tmpl = YUD.get('comment-inline-form-template').innerHTML;
669 var tmpl = YUD.get('comment-inline-form-template').innerHTML;
774 tmpl = tmpl.format(f_path, line);
670 tmpl = tmpl.format(f_path, line);
775 var form = tableTr('comment-form-inline',tmpl)
671 var form = tableTr('comment-form-inline',tmpl)
776
672
777 // create event for hide button
673 // create event for hide button
778 form = new YAHOO.util.Element(form);
674 form = new YAHOO.util.Element(form);
779 var form_hide_button = new YAHOO.util.Element(YUD.getElementsByClassName('hide-inline-form',null,form)[0]);
675 var form_hide_button = new YAHOO.util.Element(YUD.getElementsByClassName('hide-inline-form',null,form)[0]);
780 form_hide_button.on('click', function(e) {
676 form_hide_button.on('click', function(e) {
781 var newtr = e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode;
677 var newtr = e.currentTarget.parentNode.parentNode.parentNode.parentNode.parentNode;
782 if(YUD.hasClass(newtr.nextElementSibling,'inline-comments-button')){
678 if(YUD.hasClass(newtr.nextElementSibling,'inline-comments-button')){
783 YUD.setStyle(newtr.nextElementSibling,'display','');
679 YUD.setStyle(newtr.nextElementSibling,'display','');
784 }
680 }
785 removeInlineForm(newtr);
681 removeInlineForm(newtr);
786 YUD.removeClass(parent_tr, 'form-open');
682 YUD.removeClass(parent_tr, 'form-open');
787 YUD.removeClass(parent_tr, 'hl-comment');
683 YUD.removeClass(parent_tr, 'hl-comment');
788
684
789 });
685 });
790
686
791 return form
687 return form
792 };
688 };
793
689
794 /**
690 /**
795 * Inject inline comment for on given TR this tr should be always an .line
691 * Inject inline comment for on given TR this tr should be always an .line
796 * tr containing the line. Code will detect comment, and always put the comment
692 * tr containing the line. Code will detect comment, and always put the comment
797 * block at the very bottom
693 * block at the very bottom
798 */
694 */
799 var injectInlineForm = function(tr){
695 var injectInlineForm = function(tr){
800 if(!YUD.hasClass(tr, 'line')){
696 if(!YUD.hasClass(tr, 'line')){
801 return
697 return
802 }
698 }
803 var submit_url = AJAX_COMMENT_URL;
699 var submit_url = AJAX_COMMENT_URL;
804 var _td = YUD.getElementsByClassName('code',null,tr)[0];
700 var _td = YUD.getElementsByClassName('code',null,tr)[0];
805 if(YUD.hasClass(tr,'form-open') || YUD.hasClass(tr,'context') || YUD.hasClass(_td,'no-comment')){
701 if(YUD.hasClass(tr,'form-open') || YUD.hasClass(tr,'context') || YUD.hasClass(_td,'no-comment')){
806 return
702 return
807 }
703 }
808 YUD.addClass(tr,'form-open');
704 YUD.addClass(tr,'form-open');
809 YUD.addClass(tr,'hl-comment');
705 YUD.addClass(tr,'hl-comment');
810 var node = YUD.getElementsByClassName('full_f_path',null,tr.parentNode.parentNode.parentNode)[0];
706 var node = YUD.getElementsByClassName('full_f_path',null,tr.parentNode.parentNode.parentNode)[0];
811 var f_path = YUD.getAttribute(node,'path');
707 var f_path = YUD.getAttribute(node,'path');
812 var lineno = getLineNo(tr);
708 var lineno = getLineNo(tr);
813 var form = createInlineForm(tr, f_path, lineno, submit_url);
709 var form = createInlineForm(tr, f_path, lineno, submit_url);
814
710
815 var parent = tr;
711 var parent = tr;
816 while (1){
712 while (1){
817 var n = parent.nextElementSibling;
713 var n = parent.nextElementSibling;
818 // next element are comments !
714 // next element are comments !
819 if(YUD.hasClass(n,'inline-comments')){
715 if(YUD.hasClass(n,'inline-comments')){
820 parent = n;
716 parent = n;
821 }
717 }
822 else{
718 else{
823 break;
719 break;
824 }
720 }
825 }
721 }
826 YUD.insertAfter(form,parent);
722 YUD.insertAfter(form,parent);
827 var f = YUD.get(form);
723 var f = YUD.get(form);
828 var overlay = YUD.getElementsByClassName('overlay',null,f)[0];
724 var overlay = YUD.getElementsByClassName('overlay',null,f)[0];
829 var _form = YUD.getElementsByClassName('inline-form',null,f)[0];
725 var _form = YUD.getElementsByClassName('inline-form',null,f)[0];
830
726
831 YUE.on(YUD.get(_form), 'submit',function(e){
727 YUE.on(YUD.get(_form), 'submit',function(e){
832 YUE.preventDefault(e);
728 YUE.preventDefault(e);
833
729
834 //ajax submit
730 //ajax submit
835 var text = YUD.get('text_'+lineno).value;
731 var text = YUD.get('text_'+lineno).value;
836 var postData = {
732 var postData = {
837 'text':text,
733 'text':text,
838 'f_path':f_path,
734 'f_path':f_path,
839 'line':lineno
735 'line':lineno
840 };
736 };
841
737
842 if(lineno === undefined){
738 if(lineno === undefined){
843 alert('missing line !');
739 alert('missing line !');
844 return
740 return
845 }
741 }
846 if(f_path === undefined){
742 if(f_path === undefined){
847 alert('missing file path !');
743 alert('missing file path !');
848 return
744 return
849 }
745 }
850
746
851 if(text == ""){
747 if(text == ""){
852 return
748 return
853 }
749 }
854
750
855 var success = function(o){
751 var success = function(o){
856 YUD.removeClass(tr, 'form-open');
752 YUD.removeClass(tr, 'form-open');
857 removeInlineForm(f);
753 removeInlineForm(f);
858 var json_data = JSON.parse(o.responseText);
754 var json_data = JSON.parse(o.responseText);
859 renderInlineComment(json_data);
755 renderInlineComment(json_data);
860 };
756 };
861
757
862 if (YUD.hasClass(overlay,'overlay')){
758 if (YUD.hasClass(overlay,'overlay')){
863 var w = _form.offsetWidth;
759 var w = _form.offsetWidth;
864 var h = _form.offsetHeight;
760 var h = _form.offsetHeight;
865 YUD.setStyle(overlay,'width',w+'px');
761 YUD.setStyle(overlay,'width',w+'px');
866 YUD.setStyle(overlay,'height',h+'px');
762 YUD.setStyle(overlay,'height',h+'px');
867 }
763 }
868 YUD.addClass(overlay, 'submitting');
764 YUD.addClass(overlay, 'submitting');
869
765
870 ajaxPOST(submit_url, postData, success);
766 ajaxPOST(submit_url, postData, success);
871 });
767 });
872
768
873 YUE.on('preview-btn_'+lineno, 'click', function(e){
769 YUE.on('preview-btn_'+lineno, 'click', function(e){
874 var _text = YUD.get('text_'+lineno).value;
770 var _text = YUD.get('text_'+lineno).value;
875 if(!_text){
771 if(!_text){
876 return
772 return
877 }
773 }
878 var post_data = {'text': _text};
774 var post_data = {'text': _text};
879 YUD.addClass('preview-box_'+lineno, 'unloaded');
775 YUD.addClass('preview-box_'+lineno, 'unloaded');
880 YUD.get('preview-box_'+lineno).innerHTML = _TM['Loading ...'];
776 YUD.get('preview-box_'+lineno).innerHTML = _TM['Loading ...'];
881 YUD.setStyle('edit-container_'+lineno, 'display', 'none');
777 YUD.setStyle('edit-container_'+lineno, 'display', 'none');
882 YUD.setStyle('preview-container_'+lineno, 'display', '');
778 YUD.setStyle('preview-container_'+lineno, 'display', '');
883
779
884 var url = pyroutes.url('changeset_comment_preview', {'repo_name': REPO_NAME});
780 var url = pyroutes.url('changeset_comment_preview', {'repo_name': REPO_NAME});
885 ajaxPOST(url,post_data,function(o){
781 ajaxPOST(url,post_data,function(o){
886 YUD.get('preview-box_'+lineno).innerHTML = o.responseText;
782 YUD.get('preview-box_'+lineno).innerHTML = o.responseText;
887 YUD.removeClass('preview-box_'+lineno, 'unloaded');
783 YUD.removeClass('preview-box_'+lineno, 'unloaded');
888 })
784 })
889 })
785 })
890 YUE.on('edit-btn_'+lineno, 'click', function(e){
786 YUE.on('edit-btn_'+lineno, 'click', function(e){
891 YUD.setStyle('edit-container_'+lineno, 'display', '');
787 YUD.setStyle('edit-container_'+lineno, 'display', '');
892 YUD.setStyle('preview-container_'+lineno, 'display', 'none');
788 YUD.setStyle('preview-container_'+lineno, 'display', 'none');
893 })
789 })
894
790
895
896 setTimeout(function(){
791 setTimeout(function(){
897 // callbacks
792 // callbacks
898 tooltip_activate();
793 tooltip_activate();
899 MentionsAutoComplete('text_'+lineno, 'mentions_container_'+lineno,
794 MentionsAutoComplete('text_'+lineno, 'mentions_container_'+lineno,
900 _USERS_AC_DATA, _GROUPS_AC_DATA);
795 _USERS_AC_DATA, _GROUPS_AC_DATA);
901 var _e = YUD.get('text_'+lineno);
796 var _e = YUD.get('text_'+lineno);
902 if(_e){
797 if(_e){
903 _e.focus();
798 _e.focus();
904 }
799 }
905 },10)
800 },10)
906 };
801 };
907
802
908 var deleteComment = function(comment_id){
803 var deleteComment = function(comment_id){
909 var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__',comment_id);
804 var url = AJAX_COMMENT_DELETE_URL.replace('__COMMENT_ID__',comment_id);
910 var postData = {'_method':'delete'};
805 var postData = {'_method':'delete'};
911 var success = function(o){
806 var success = function(o){
912 var n = YUD.get('comment-tr-'+comment_id);
807 var n = YUD.get('comment-tr-'+comment_id);
913 var root = prevElementSibling(prevElementSibling(n));
808 var root = prevElementSibling(prevElementSibling(n));
914 n.parentNode.removeChild(n);
809 n.parentNode.removeChild(n);
915
810
916 // scann nodes, and attach add button to last one only for TR
811 // scann nodes, and attach add button to last one only for TR
917 // which are the inline comments
812 // which are the inline comments
918 if(root && root.tagName == 'TR'){
813 if(root && root.tagName == 'TR'){
919 placeAddButton(root);
814 placeAddButton(root);
920 }
815 }
921 }
816 }
922 ajaxPOST(url,postData,success);
817 ajaxPOST(url,postData,success);
923 }
818 }
924
819
925 var createInlineAddButton = function(tr){
820 var createInlineAddButton = function(tr){
926
821
927 var label = TRANSLATION_MAP['Add another comment'];
822 var label = TRANSLATION_MAP['Add another comment'];
928
823
929 var html_el = document.createElement('div');
824 var html_el = document.createElement('div');
930 YUD.addClass(html_el, 'add-comment');
825 YUD.addClass(html_el, 'add-comment');
931 html_el.innerHTML = '<span class="ui-btn">{0}</span>'.format(label);
826 html_el.innerHTML = '<span class="ui-btn">{0}</span>'.format(label);
932
827
933 var add = new YAHOO.util.Element(html_el);
828 var add = new YAHOO.util.Element(html_el);
934 add.on('click', function(e) {
829 add.on('click', function(e) {
935 injectInlineForm(tr);
830 injectInlineForm(tr);
936 });
831 });
937 return add;
832 return add;
938 };
833 };
939
834
940 var getLineNo = function(tr) {
835 var getLineNo = function(tr) {
941 var line;
836 var line;
942 var o = tr.children[0].id.split('_');
837 var o = tr.children[0].id.split('_');
943 var n = tr.children[1].id.split('_');
838 var n = tr.children[1].id.split('_');
944
839
945 if (n.length >= 2) {
840 if (n.length >= 2) {
946 line = n[n.length-1];
841 line = n[n.length-1];
947 } else if (o.length >= 2) {
842 } else if (o.length >= 2) {
948 line = o[o.length-1];
843 line = o[o.length-1];
949 }
844 }
950
845
951 return line
846 return line
952 };
847 };
953
848
954 var placeAddButton = function(target_tr){
849 var placeAddButton = function(target_tr){
955 if(!target_tr){
850 if(!target_tr){
956 return
851 return
957 }
852 }
958 var last_node = target_tr;
853 var last_node = target_tr;
959 //scann
854 //scann
960 while (1){
855 while (1){
961 var n = last_node.nextElementSibling;
856 var n = last_node.nextElementSibling;
962 // next element are comments !
857 // next element are comments !
963 if(YUD.hasClass(n,'inline-comments')){
858 if(YUD.hasClass(n,'inline-comments')){
964 last_node = n;
859 last_node = n;
965 //also remove the comment button from previous
860 //also remove the comment button from previous
966 var comment_add_buttons = YUD.getElementsByClassName('add-comment',null,last_node);
861 var comment_add_buttons = YUD.getElementsByClassName('add-comment',null,last_node);
967 for(var i=0;i<comment_add_buttons.length;i++){
862 for(var i=0;i<comment_add_buttons.length;i++){
968 var b = comment_add_buttons[i];
863 var b = comment_add_buttons[i];
969 b.parentNode.removeChild(b);
864 b.parentNode.removeChild(b);
970 }
865 }
971 }
866 }
972 else{
867 else{
973 break;
868 break;
974 }
869 }
975 }
870 }
976
871
977 var add = createInlineAddButton(target_tr);
872 var add = createInlineAddButton(target_tr);
978 // get the comment div
873 // get the comment div
979 var comment_block = YUD.getElementsByClassName('comment',null,last_node)[0];
874 var comment_block = YUD.getElementsByClassName('comment',null,last_node)[0];
980 // attach add button
875 // attach add button
981 YUD.insertAfter(add,comment_block);
876 YUD.insertAfter(add,comment_block);
982 }
877 }
983
878
984 /**
879 /**
985 * Places the inline comment into the changeset block in proper line position
880 * Places the inline comment into the changeset block in proper line position
986 */
881 */
987 var placeInline = function(target_container,lineno,html){
882 var placeInline = function(target_container,lineno,html){
988 var lineid = "{0}_{1}".format(target_container,lineno);
883 var lineid = "{0}_{1}".format(target_container,lineno);
989 var target_line = YUD.get(lineid);
884 var target_line = YUD.get(lineid);
990 var comment = new YAHOO.util.Element(tableTr('inline-comments',html))
885 var comment = new YAHOO.util.Element(tableTr('inline-comments',html))
991
886
992 // check if there are comments already !
887 // check if there are comments already !
993 var parent = target_line.parentNode;
888 var parent = target_line.parentNode;
994 var root_parent = parent;
889 var root_parent = parent;
995 while (1){
890 while (1){
996 var n = parent.nextElementSibling;
891 var n = parent.nextElementSibling;
997 // next element are comments !
892 // next element are comments !
998 if(YUD.hasClass(n,'inline-comments')){
893 if(YUD.hasClass(n,'inline-comments')){
999 parent = n;
894 parent = n;
1000 }
895 }
1001 else{
896 else{
1002 break;
897 break;
1003 }
898 }
1004 }
899 }
1005 // put in the comment at the bottom
900 // put in the comment at the bottom
1006 YUD.insertAfter(comment,parent);
901 YUD.insertAfter(comment,parent);
1007
902
1008 // scann nodes, and attach add button to last one
903 // scann nodes, and attach add button to last one
1009 placeAddButton(root_parent);
904 placeAddButton(root_parent);
1010
905
1011 return target_line;
906 return target_line;
1012 }
907 }
1013
908
1014 /**
909 /**
1015 * make a single inline comment and place it inside
910 * make a single inline comment and place it inside
1016 */
911 */
1017 var renderInlineComment = function(json_data){
912 var renderInlineComment = function(json_data){
1018 try{
913 try{
1019 var html = json_data['rendered_text'];
914 var html = json_data['rendered_text'];
1020 var lineno = json_data['line_no'];
915 var lineno = json_data['line_no'];
1021 var target_id = json_data['target_id'];
916 var target_id = json_data['target_id'];
1022 placeInline(target_id, lineno, html);
917 placeInline(target_id, lineno, html);
1023
1024 }catch(e){
918 }catch(e){
1025 console.log(e);
919 console.log(e);
1026 }
920 }
1027 }
921 }
1028
922
1029 /**
923 /**
1030 * Iterates over all the inlines, and places them inside proper blocks of data
924 * Iterates over all the inlines, and places them inside proper blocks of data
1031 */
925 */
1032 var renderInlineComments = function(file_comments){
926 var renderInlineComments = function(file_comments){
1033 for (f in file_comments){
927 for (f in file_comments){
1034 // holding all comments for a FILE
928 // holding all comments for a FILE
1035 var box = file_comments[f];
929 var box = file_comments[f];
1036
930
1037 var target_id = YUD.getAttribute(box,'target_id');
931 var target_id = YUD.getAttribute(box,'target_id');
1038 // actually comments with line numbers
932 // actually comments with line numbers
1039 var comments = box.children;
933 var comments = box.children;
1040 for(var i=0; i<comments.length; i++){
934 for(var i=0; i<comments.length; i++){
1041 var data = {
935 var data = {
1042 'rendered_text': comments[i].outerHTML,
936 'rendered_text': comments[i].outerHTML,
1043 'line_no': YUD.getAttribute(comments[i],'line'),
937 'line_no': YUD.getAttribute(comments[i],'line'),
1044 'target_id': target_id
938 'target_id': target_id
1045 }
939 }
1046 renderInlineComment(data);
940 renderInlineComment(data);
1047 }
941 }
1048 }
942 }
1049 }
943 }
1050
944
1051 var fileBrowserListeners = function(current_url, node_list_url, url_base){
945 var fileBrowserListeners = function(current_url, node_list_url, url_base){
1052 var current_url_branch = +"?branch=__BRANCH__";
946 var current_url_branch = +"?branch=__BRANCH__";
1053
947
1054 YUE.on('stay_at_branch','click',function(e){
948 YUE.on('stay_at_branch','click',function(e){
1055 if(e.target.checked){
949 if(e.target.checked){
1056 var uri = current_url_branch;
950 var uri = current_url_branch;
1057 uri = uri.replace('__BRANCH__',e.target.value);
951 uri = uri.replace('__BRANCH__',e.target.value);
1058 window.location = uri;
952 window.location = uri;
1059 }
953 }
1060 else{
954 else{
1061 window.location = current_url;
955 window.location = current_url;
1062 }
956 }
1063 })
957 })
1064
958
1065 var n_filter = YUD.get('node_filter');
959 var n_filter = YUD.get('node_filter');
1066 var F = YAHOO.namespace('node_filter');
960 var F = YAHOO.namespace('node_filter');
1067
961
1068 F.filterTimeout = null;
962 F.filterTimeout = null;
1069 var nodes = null;
963 var nodes = null;
1070
964
1071 F.initFilter = function(){
965 F.initFilter = function(){
1072 YUD.setStyle('node_filter_box_loading','display','');
966 YUD.setStyle('node_filter_box_loading','display','');
1073 YUD.setStyle('search_activate_id','display','none');
967 YUD.setStyle('search_activate_id','display','none');
1074 YUD.setStyle('add_node_id','display','none');
968 YUD.setStyle('add_node_id','display','none');
1075 YUC.initHeader('X-PARTIAL-XHR',true);
969 YUC.initHeader('X-PARTIAL-XHR',true);
1076 YUC.asyncRequest('GET', node_list_url, {
970 YUC.asyncRequest('GET', node_list_url, {
1077 success:function(o){
971 success:function(o){
1078 nodes = JSON.parse(o.responseText).nodes;
972 nodes = JSON.parse(o.responseText).nodes;
1079 YUD.setStyle('node_filter_box_loading','display','none');
973 YUD.setStyle('node_filter_box_loading','display','none');
1080 YUD.setStyle('node_filter_box','display','');
974 YUD.setStyle('node_filter_box','display','');
1081 n_filter.focus();
975 n_filter.focus();
1082 if(YUD.hasClass(n_filter,'init')){
976 if(YUD.hasClass(n_filter,'init')){
1083 n_filter.value = '';
977 n_filter.value = '';
1084 YUD.removeClass(n_filter,'init');
978 YUD.removeClass(n_filter,'init');
1085 }
979 }
1086 },
980 },
1087 failure:function(o){
981 failure:function(o){
1088 console.log('failed to load');
982 console.log('failed to load');
1089 }
983 }
1090 },null);
984 },null);
1091 }
985 }
1092
986
1093 F.updateFilter = function(e) {
987 F.updateFilter = function(e) {
1094
1095 return function(){
988 return function(){
1096 // Reset timeout
989 // Reset timeout
1097 F.filterTimeout = null;
990 F.filterTimeout = null;
1098 var query = e.target.value.toLowerCase();
991 var query = e.target.value.toLowerCase();
1099 var match = [];
992 var match = [];
1100 var matches = 0;
993 var matches = 0;
1101 var matches_max = 20;
994 var matches_max = 20;
1102 if (query != ""){
995 if (query != ""){
1103 for(var i=0;i<nodes.length;i++){
996 for(var i=0;i<nodes.length;i++){
1104
1105 var pos = nodes[i].name.toLowerCase().indexOf(query)
997 var pos = nodes[i].name.toLowerCase().indexOf(query)
1106 if(query && pos != -1){
998 if(query && pos != -1){
1107
1108 matches++
999 matches++
1109 //show only certain amount to not kill browser
1000 //show only certain amount to not kill browser
1110 if (matches > matches_max){
1001 if (matches > matches_max){
1111 break;
1002 break;
1112 }
1003 }
1113
1004
1114 var n = nodes[i].name;
1005 var n = nodes[i].name;
1115 var t = nodes[i].type;
1006 var t = nodes[i].type;
1116 var n_hl = n.substring(0,pos)
1007 var n_hl = n.substring(0,pos)
1117 +"<b>{0}</b>".format(n.substring(pos,pos+query.length))
1008 +"<b>{0}</b>".format(n.substring(pos,pos+query.length))
1118 +n.substring(pos+query.length)
1009 +n.substring(pos+query.length)
1119 var new_url = url_base.replace('__FPATH__',n);
1010 var new_url = url_base.replace('__FPATH__',n);
1120 match.push('<tr><td><a class="browser-{0}" href="{1}">{2}</a></td><td colspan="5"></td></tr>'.format(t,new_url,n_hl));
1011 match.push('<tr><td><a class="browser-{0}" href="{1}">{2}</a></td><td colspan="5"></td></tr>'.format(t,new_url,n_hl));
1121 }
1012 }
1122 if(match.length >= matches_max){
1013 if(match.length >= matches_max){
1123 match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['Search truncated']));
1014 match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['Search truncated']));
1124 }
1015 }
1125 }
1016 }
1126 }
1017 }
1127 if(query != ""){
1018 if(query != ""){
1128 YUD.setStyle('tbody','display','none');
1019 YUD.setStyle('tbody','display','none');
1129 YUD.setStyle('tbody_filtered','display','');
1020 YUD.setStyle('tbody_filtered','display','');
1130
1021
1131 if (match.length==0){
1022 if (match.length==0){
1132 match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['No matching files']));
1023 match.push('<tr><td>{0}</td><td colspan="5"></td></tr>'.format(_TM['No matching files']));
1133 }
1024 }
1134
1025
1135 YUD.get('tbody_filtered').innerHTML = match.join("");
1026 YUD.get('tbody_filtered').innerHTML = match.join("");
1136 }
1027 }
1137 else{
1028 else{
1138 YUD.setStyle('tbody','display','');
1029 YUD.setStyle('tbody','display','');
1139 YUD.setStyle('tbody_filtered','display','none');
1030 YUD.setStyle('tbody_filtered','display','none');
1140 }
1031 }
1141
1142 }
1032 }
1143 };
1033 };
1144
1034
1145 YUE.on(YUD.get('filter_activate'),'click',function(){
1035 YUE.on(YUD.get('filter_activate'),'click',function(){
1146 F.initFilter();
1036 F.initFilter();
1147 })
1037 })
1148 YUE.on(n_filter,'click',function(){
1038 YUE.on(n_filter,'click',function(){
1149 if(YUD.hasClass(n_filter,'init')){
1039 if(YUD.hasClass(n_filter,'init')){
1150 n_filter.value = '';
1040 n_filter.value = '';
1151 YUD.removeClass(n_filter,'init');
1041 YUD.removeClass(n_filter,'init');
1152 }
1042 }
1153 });
1043 });
1154 YUE.on(n_filter,'keyup',function(e){
1044 YUE.on(n_filter,'keyup',function(e){
1155 clearTimeout(F.filterTimeout);
1045 clearTimeout(F.filterTimeout);
1156 F.filterTimeout = setTimeout(F.updateFilter(e),600);
1046 F.filterTimeout = setTimeout(F.updateFilter(e),600);
1157 });
1047 });
1158 };
1048 };
1159
1049
1160
1050
1161 var initCodeMirror = function(textAreadId,resetUrl){
1051 var initCodeMirror = function(textAreadId,resetUrl){
1162 var myCodeMirror = CodeMirror.fromTextArea(YUD.get(textAreadId),{
1052 var myCodeMirror = CodeMirror.fromTextArea(YUD.get(textAreadId),{
1163 mode: "null",
1053 mode: "null",
1164 lineNumbers:true,
1054 lineNumbers:true,
1165 indentUnit: 4
1055 indentUnit: 4
1166 });
1056 });
1167 YUE.on('reset','click',function(e){
1057 YUE.on('reset','click',function(e){
1168 window.location=resetUrl
1058 window.location=resetUrl
1169 });
1059 });
1170
1060
1171 YUE.on('file_enable','click',function(){
1061 YUE.on('file_enable','click',function(){
1172 YUD.setStyle('editor_container','display','');
1062 YUD.setStyle('editor_container','display','');
1173 YUD.setStyle('upload_file_container','display','none');
1063 YUD.setStyle('upload_file_container','display','none');
1174 YUD.setStyle('filename_container','display','');
1064 YUD.setStyle('filename_container','display','');
1175 });
1065 });
1176
1066
1177 YUE.on('upload_file_enable','click',function(){
1067 YUE.on('upload_file_enable','click',function(){
1178 YUD.setStyle('editor_container','display','none');
1068 YUD.setStyle('editor_container','display','none');
1179 YUD.setStyle('upload_file_container','display','');
1069 YUD.setStyle('upload_file_container','display','');
1180 YUD.setStyle('filename_container','display','none');
1070 YUD.setStyle('filename_container','display','none');
1181 });
1071 });
1182
1072
1183 return myCodeMirror
1073 return myCodeMirror
1184 };
1074 };
1185
1075
1186 var setCodeMirrorMode = function(codeMirrorInstance, mode) {
1076 var setCodeMirrorMode = function(codeMirrorInstance, mode) {
1187 codeMirrorInstance.setOption("mode", mode);
1077 codeMirrorInstance.setOption("mode", mode);
1188 CodeMirror.autoLoadMode(codeMirrorInstance, mode);
1078 CodeMirror.autoLoadMode(codeMirrorInstance, mode);
1189 }
1079 }
1190
1080
1191
1081
1192 var getIdentNode = function(n){
1082 var getIdentNode = function(n){
1193 //iterate thru nodes untill matched interesting node !
1083 //iterate thru nodes untill matched interesting node !
1194
1084
1195 if (typeof n == 'undefined'){
1085 if (typeof n == 'undefined'){
1196 return -1
1086 return -1
1197 }
1087 }
1198
1088
1199 if(typeof n.id != "undefined" && n.id.match('L[0-9]+')){
1089 if(typeof n.id != "undefined" && n.id.match('L[0-9]+')){
1200 return n
1090 return n
1201 }
1091 }
1202 else{
1092 else{
1203 return getIdentNode(n.parentNode);
1093 return getIdentNode(n.parentNode);
1204 }
1094 }
1205 };
1095 };
1206
1096
1207 var getSelectionLink = function(e) {
1097 var getSelectionLink = function(e) {
1208
1209 //get selection from start/to nodes
1098 //get selection from start/to nodes
1210 if (typeof window.getSelection != "undefined") {
1099 if (typeof window.getSelection != "undefined") {
1211 s = window.getSelection();
1100 s = window.getSelection();
1212
1101
1213 from = getIdentNode(s.anchorNode);
1102 from = getIdentNode(s.anchorNode);
1214 till = getIdentNode(s.focusNode);
1103 till = getIdentNode(s.focusNode);
1215
1104
1216 f_int = parseInt(from.id.replace('L',''));
1105 f_int = parseInt(from.id.replace('L',''));
1217 t_int = parseInt(till.id.replace('L',''));
1106 t_int = parseInt(till.id.replace('L',''));
1218
1107
1219 if (f_int > t_int){
1108 if (f_int > t_int){
1220 //highlight from bottom
1109 //highlight from bottom
1221 offset = -35;
1110 offset = -35;
1222 ranges = [t_int,f_int];
1111 ranges = [t_int,f_int];
1223
1112
1224 }
1113 }
1225 else{
1114 else{
1226 //highligth from top
1115 //highligth from top
1227 offset = 35;
1116 offset = 35;
1228 ranges = [f_int,t_int];
1117 ranges = [f_int,t_int];
1229 }
1118 }
1230 // if we select more than 2 lines
1119 // if we select more than 2 lines
1231 if (ranges[0] != ranges[1]){
1120 if (ranges[0] != ranges[1]){
1232 if(YUD.get('linktt') == null){
1121 if(YUD.get('linktt') == null){
1233 hl_div = document.createElement('div');
1122 hl_div = document.createElement('div');
1234 hl_div.id = 'linktt';
1123 hl_div.id = 'linktt';
1235 }
1124 }
1236 hl_div.innerHTML = '';
1125 hl_div.innerHTML = '';
1237
1126
1238 anchor = '#L'+ranges[0]+'-'+ranges[1];
1127 anchor = '#L'+ranges[0]+'-'+ranges[1];
1239 var link = document.createElement('a');
1128 var link = document.createElement('a');
1240 link.href = location.href.substring(0,location.href.indexOf('#'))+anchor;
1129 link.href = location.href.substring(0,location.href.indexOf('#'))+anchor;
1241 link.innerHTML = _TM['Selection link'];
1130 link.innerHTML = _TM['Selection link'];
1242 hl_div.appendChild(link);
1131 hl_div.appendChild(link);
1243 YUD.get('body').appendChild(hl_div);
1132 YUD.get('body').appendChild(hl_div);
1244
1133
1245 xy = YUD.getXY(till.id);
1134 xy = YUD.getXY(till.id);
1246
1135
1247 YUD.addClass('linktt', 'hl-tip-box');
1136 YUD.addClass('linktt', 'hl-tip-box');
1248 YUD.setStyle('linktt','top',xy[1]+offset+'px');
1137 YUD.setStyle('linktt','top',xy[1]+offset+'px');
1249 YUD.setStyle('linktt','left',xy[0]+'px');
1138 YUD.setStyle('linktt','left',xy[0]+'px');
1250 YUD.setStyle('linktt','visibility','visible');
1139 YUD.setStyle('linktt','visibility','visible');
1251
1140
1252 }
1141 }
1253 else{
1142 else{
1254 YUD.setStyle('linktt','visibility','hidden');
1143 YUD.setStyle('linktt','visibility','hidden');
1255 }
1144 }
1256 }
1145 }
1257 };
1146 };
1258
1147
1259 var deleteNotification = function(url, notification_id,callbacks){
1148 var deleteNotification = function(url, notification_id,callbacks){
1260 var callback = {
1149 var callback = {
1261 success:function(o){
1150 success:function(o){
1262 var obj = YUD.get(String("notification_"+notification_id));
1151 var obj = YUD.get(String("notification_"+notification_id));
1263 if(obj.parentNode !== undefined){
1152 if(obj.parentNode !== undefined){
1264 obj.parentNode.removeChild(obj);
1153 obj.parentNode.removeChild(obj);
1265 }
1154 }
1266 _run_callbacks(callbacks);
1155 _run_callbacks(callbacks);
1267 },
1156 },
1268 failure:function(o){
1157 failure:function(o){
1269 alert("error");
1158 alert("error");
1270 },
1159 },
1271 };
1160 };
1272 var postData = '_method=delete';
1161 var postData = '_method=delete';
1273 var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
1162 var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
1274 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl,
1163 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl,
1275 callback, postData);
1164 callback, postData);
1276 };
1165 };
1277
1166
1278 var readNotification = function(url, notification_id,callbacks){
1167 var readNotification = function(url, notification_id,callbacks){
1279 var callback = {
1168 var callback = {
1280 success:function(o){
1169 success:function(o){
1281 var obj = YUD.get(String("notification_"+notification_id));
1170 var obj = YUD.get(String("notification_"+notification_id));
1282 YUD.removeClass(obj, 'unread');
1171 YUD.removeClass(obj, 'unread');
1283 var r_button = YUD.getElementsByClassName('read-notification',null,obj.children[0])[0];
1172 var r_button = YUD.getElementsByClassName('read-notification',null,obj.children[0])[0];
1284
1173
1285 if(r_button.parentNode !== undefined){
1174 if(r_button.parentNode !== undefined){
1286 r_button.parentNode.removeChild(r_button);
1175 r_button.parentNode.removeChild(r_button);
1287 }
1176 }
1288 _run_callbacks(callbacks);
1177 _run_callbacks(callbacks);
1289 },
1178 },
1290 failure:function(o){
1179 failure:function(o){
1291 alert("error");
1180 alert("error");
1292 },
1181 },
1293 };
1182 };
1294 var postData = '_method=put';
1183 var postData = '_method=put';
1295 var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
1184 var sUrl = url.replace('__NOTIFICATION_ID__',notification_id);
1296 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl,
1185 var request = YAHOO.util.Connect.asyncRequest('POST', sUrl,
1297 callback, postData);
1186 callback, postData);
1298 };
1187 };
1299
1188
1300 /** MEMBERS AUTOCOMPLETE WIDGET **/
1189 /** MEMBERS AUTOCOMPLETE WIDGET **/
1301
1190
1302 var MembersAutoComplete = function (divid, cont, users_list, groups_list) {
1191 var MembersAutoComplete = function (divid, cont, users_list, groups_list) {
1303 var myUsers = users_list;
1192 var myUsers = users_list;
1304 var myGroups = groups_list;
1193 var myGroups = groups_list;
1305
1194
1306 // Define a custom search function for the DataSource of users
1195 // Define a custom search function for the DataSource of users
1307 var matchUsers = function (sQuery) {
1196 var matchUsers = function (sQuery) {
1308 // Case insensitive matching
1197 // Case insensitive matching
1309 var query = sQuery.toLowerCase();
1198 var query = sQuery.toLowerCase();
1310 var i = 0;
1199 var i = 0;
1311 var l = myUsers.length;
1200 var l = myUsers.length;
1312 var matches = [];
1201 var matches = [];
1313
1202
1314 // Match against each name of each contact
1203 // Match against each name of each contact
1315 for (; i < l; i++) {
1204 for (; i < l; i++) {
1316 contact = myUsers[i];
1205 contact = myUsers[i];
1317 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1206 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1318 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1207 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1319 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1208 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1320 matches[matches.length] = contact;
1209 matches[matches.length] = contact;
1321 }
1210 }
1322 }
1211 }
1323 return matches;
1212 return matches;
1324 };
1213 };
1325
1214
1326 // Define a custom search function for the DataSource of userGroups
1215 // Define a custom search function for the DataSource of userGroups
1327 var matchGroups = function (sQuery) {
1216 var matchGroups = function (sQuery) {
1328 // Case insensitive matching
1217 // Case insensitive matching
1329 var query = sQuery.toLowerCase();
1218 var query = sQuery.toLowerCase();
1330 var i = 0;
1219 var i = 0;
1331 var l = myGroups.length;
1220 var l = myGroups.length;
1332 var matches = [];
1221 var matches = [];
1333
1222
1334 // Match against each name of each contact
1223 // Match against each name of each contact
1335 for (; i < l; i++) {
1224 for (; i < l; i++) {
1336 matched_group = myGroups[i];
1225 matched_group = myGroups[i];
1337 if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
1226 if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
1338 matches[matches.length] = matched_group;
1227 matches[matches.length] = matched_group;
1339 }
1228 }
1340 }
1229 }
1341 return matches;
1230 return matches;
1342 };
1231 };
1343
1232
1344 //match all
1233 //match all
1345 var matchAll = function (sQuery) {
1234 var matchAll = function (sQuery) {
1346 u = matchUsers(sQuery);
1235 u = matchUsers(sQuery);
1347 g = matchGroups(sQuery);
1236 g = matchGroups(sQuery);
1348 return u.concat(g);
1237 return u.concat(g);
1349 };
1238 };
1350
1239
1351 // DataScheme for members
1240 // DataScheme for members
1352 var memberDS = new YAHOO.util.FunctionDataSource(matchAll);
1241 var memberDS = new YAHOO.util.FunctionDataSource(matchAll);
1353 memberDS.responseSchema = {
1242 memberDS.responseSchema = {
1354 fields: ["id", "fname", "lname", "nname", "grname", "grmembers", "gravatar_lnk"]
1243 fields: ["id", "fname", "lname", "nname", "grname", "grmembers", "gravatar_lnk"]
1355 };
1244 };
1356
1245
1357 // DataScheme for owner
1246 // DataScheme for owner
1358 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1247 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1359 ownerDS.responseSchema = {
1248 ownerDS.responseSchema = {
1360 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1249 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1361 };
1250 };
1362
1251
1363 // Instantiate AutoComplete for perms
1252 // Instantiate AutoComplete for perms
1364 var membersAC = new YAHOO.widget.AutoComplete(divid, cont, memberDS);
1253 var membersAC = new YAHOO.widget.AutoComplete(divid, cont, memberDS);
1365 membersAC.useShadow = false;
1254 membersAC.useShadow = false;
1366 membersAC.resultTypeList = false;
1255 membersAC.resultTypeList = false;
1367 membersAC.animVert = false;
1256 membersAC.animVert = false;
1368 membersAC.animHoriz = false;
1257 membersAC.animHoriz = false;
1369 membersAC.animSpeed = 0.1;
1258 membersAC.animSpeed = 0.1;
1370
1259
1371 // Instantiate AutoComplete for owner
1260 // Instantiate AutoComplete for owner
1372 var ownerAC = new YAHOO.widget.AutoComplete("user", "owner_container", ownerDS);
1261 var ownerAC = new YAHOO.widget.AutoComplete("user", "owner_container", ownerDS);
1373 ownerAC.useShadow = false;
1262 ownerAC.useShadow = false;
1374 ownerAC.resultTypeList = false;
1263 ownerAC.resultTypeList = false;
1375 ownerAC.animVert = false;
1264 ownerAC.animVert = false;
1376 ownerAC.animHoriz = false;
1265 ownerAC.animHoriz = false;
1377 ownerAC.animSpeed = 0.1;
1266 ownerAC.animSpeed = 0.1;
1378
1267
1379 // Helper highlight function for the formatter
1268 // Helper highlight function for the formatter
1380 var highlightMatch = function (full, snippet, matchindex) {
1269 var highlightMatch = function (full, snippet, matchindex) {
1381 return full.substring(0, matchindex)
1270 return full.substring(0, matchindex)
1382 + "<span class='match'>"
1271 + "<span class='match'>"
1383 + full.substr(matchindex, snippet.length)
1272 + full.substr(matchindex, snippet.length)
1384 + "</span>" + full.substring(matchindex + snippet.length);
1273 + "</span>" + full.substring(matchindex + snippet.length);
1385 };
1274 };
1386
1275
1387 // Custom formatter to highlight the matching letters
1276 // Custom formatter to highlight the matching letters
1388 var custom_formatter = function (oResultData, sQuery, sResultMatch) {
1277 var custom_formatter = function (oResultData, sQuery, sResultMatch) {
1389 var query = sQuery.toLowerCase();
1278 var query = sQuery.toLowerCase();
1390 var _gravatar = function(res, em, group){
1279 var _gravatar = function(res, em, group){
1391 if (group !== undefined){
1280 if (group !== undefined){
1392 em = '/images/icons/group.png'
1281 em = '/images/icons/group.png'
1393 }
1282 }
1394 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1283 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1395 return tmpl.format(em,res)
1284 return tmpl.format(em,res)
1396 }
1285 }
1397 // group
1286 // group
1398 if (oResultData.grname != undefined) {
1287 if (oResultData.grname != undefined) {
1399 var grname = oResultData.grname;
1288 var grname = oResultData.grname;
1400 var grmembers = oResultData.grmembers;
1289 var grmembers = oResultData.grmembers;
1401 var grnameMatchIndex = grname.toLowerCase().indexOf(query);
1290 var grnameMatchIndex = grname.toLowerCase().indexOf(query);
1402 var grprefix = "{0}: ".format(_TM['Group']);
1291 var grprefix = "{0}: ".format(_TM['Group']);
1403 var grsuffix = " (" + grmembers + " )";
1292 var grsuffix = " (" + grmembers + " )";
1404 var grsuffix = " ({0} {1})".format(grmembers, _TM['members']);
1293 var grsuffix = " ({0} {1})".format(grmembers, _TM['members']);
1405
1294
1406 if (grnameMatchIndex > -1) {
1295 if (grnameMatchIndex > -1) {
1407 return _gravatar(grprefix + highlightMatch(grname, query, grnameMatchIndex) + grsuffix,null,true);
1296 return _gravatar(grprefix + highlightMatch(grname, query, grnameMatchIndex) + grsuffix,null,true);
1408 }
1297 }
1409 return _gravatar(grprefix + oResultData.grname + grsuffix, null,true);
1298 return _gravatar(grprefix + oResultData.grname + grsuffix, null,true);
1410 // Users
1299 // Users
1411 } else if (oResultData.nname != undefined) {
1300 } else if (oResultData.nname != undefined) {
1412 var fname = oResultData.fname || "";
1301 var fname = oResultData.fname || "";
1413 var lname = oResultData.lname || "";
1302 var lname = oResultData.lname || "";
1414 var nname = oResultData.nname;
1303 var nname = oResultData.nname;
1415
1304
1416 // Guard against null value
1305 // Guard against null value
1417 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1306 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1418 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1307 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1419 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1308 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1420 displayfname, displaylname, displaynname;
1309 displayfname, displaylname, displaynname;
1421
1310
1422 if (fnameMatchIndex > -1) {
1311 if (fnameMatchIndex > -1) {
1423 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1312 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1424 } else {
1313 } else {
1425 displayfname = fname;
1314 displayfname = fname;
1426 }
1315 }
1427
1316
1428 if (lnameMatchIndex > -1) {
1317 if (lnameMatchIndex > -1) {
1429 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1318 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1430 } else {
1319 } else {
1431 displaylname = lname;
1320 displaylname = lname;
1432 }
1321 }
1433
1322
1434 if (nnameMatchIndex > -1) {
1323 if (nnameMatchIndex > -1) {
1435 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1324 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1436 } else {
1325 } else {
1437 displaynname = nname ? "(" + nname + ")" : "";
1326 displaynname = nname ? "(" + nname + ")" : "";
1438 }
1327 }
1439
1328
1440 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1329 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1441 } else {
1330 } else {
1442 return '';
1331 return '';
1443 }
1332 }
1444 };
1333 };
1445 membersAC.formatResult = custom_formatter;
1334 membersAC.formatResult = custom_formatter;
1446 ownerAC.formatResult = custom_formatter;
1335 ownerAC.formatResult = custom_formatter;
1447
1336
1448 var myHandler = function (sType, aArgs) {
1337 var myHandler = function (sType, aArgs) {
1449 var nextId = divid.split('perm_new_member_name_')[1];
1338 var nextId = divid.split('perm_new_member_name_')[1];
1450 var myAC = aArgs[0]; // reference back to the AC instance
1339 var myAC = aArgs[0]; // reference back to the AC instance
1451 var elLI = aArgs[1]; // reference to the selected LI element
1340 var elLI = aArgs[1]; // reference to the selected LI element
1452 var oData = aArgs[2]; // object literal of selected item's result data
1341 var oData = aArgs[2]; // object literal of selected item's result data
1453 //fill the autocomplete with value
1342 //fill the autocomplete with value
1454 if (oData.nname != undefined) {
1343 if (oData.nname != undefined) {
1455 //users
1344 //users
1456 myAC.getInputEl().value = oData.nname;
1345 myAC.getInputEl().value = oData.nname;
1457 YUD.get('perm_new_member_type_'+nextId).value = 'user';
1346 YUD.get('perm_new_member_type_'+nextId).value = 'user';
1458 } else {
1347 } else {
1459 //groups
1348 //groups
1460 myAC.getInputEl().value = oData.grname;
1349 myAC.getInputEl().value = oData.grname;
1461 YUD.get('perm_new_member_type_'+nextId).value = 'users_group';
1350 YUD.get('perm_new_member_type_'+nextId).value = 'users_group';
1462 }
1351 }
1463 };
1352 };
1464
1353
1465 membersAC.itemSelectEvent.subscribe(myHandler);
1354 membersAC.itemSelectEvent.subscribe(myHandler);
1466 if(ownerAC.itemSelectEvent){
1355 if(ownerAC.itemSelectEvent){
1467 ownerAC.itemSelectEvent.subscribe(myHandler);
1356 ownerAC.itemSelectEvent.subscribe(myHandler);
1468 }
1357 }
1469
1358
1470 return {
1359 return {
1471 memberDS: memberDS,
1360 memberDS: memberDS,
1472 ownerDS: ownerDS,
1361 ownerDS: ownerDS,
1473 membersAC: membersAC,
1362 membersAC: membersAC,
1474 ownerAC: ownerAC,
1363 ownerAC: ownerAC,
1475 };
1364 };
1476 }
1365 }
1477
1366
1478
1479 var MentionsAutoComplete = function (divid, cont, users_list, groups_list) {
1367 var MentionsAutoComplete = function (divid, cont, users_list, groups_list) {
1480 var myUsers = users_list;
1368 var myUsers = users_list;
1481 var myGroups = groups_list;
1369 var myGroups = groups_list;
1482
1370
1483 // Define a custom search function for the DataSource of users
1371 // Define a custom search function for the DataSource of users
1484 var matchUsers = function (sQuery) {
1372 var matchUsers = function (sQuery) {
1485 var org_sQuery = sQuery;
1373 var org_sQuery = sQuery;
1486 if(this.mentionQuery == null){
1374 if(this.mentionQuery == null){
1487 return []
1375 return []
1488 }
1376 }
1489 sQuery = this.mentionQuery;
1377 sQuery = this.mentionQuery;
1490 // Case insensitive matching
1378 // Case insensitive matching
1491 var query = sQuery.toLowerCase();
1379 var query = sQuery.toLowerCase();
1492 var i = 0;
1380 var i = 0;
1493 var l = myUsers.length;
1381 var l = myUsers.length;
1494 var matches = [];
1382 var matches = [];
1495
1383
1496 // Match against each name of each contact
1384 // Match against each name of each contact
1497 for (; i < l; i++) {
1385 for (; i < l; i++) {
1498 contact = myUsers[i];
1386 contact = myUsers[i];
1499 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1387 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1500 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1388 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1501 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1389 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1502 matches[matches.length] = contact;
1390 matches[matches.length] = contact;
1503 }
1391 }
1504 }
1392 }
1505 return matches
1393 return matches
1506 };
1394 };
1507
1395
1508 //match all
1396 //match all
1509 var matchAll = function (sQuery) {
1397 var matchAll = function (sQuery) {
1510 u = matchUsers(sQuery);
1398 u = matchUsers(sQuery);
1511 return u
1399 return u
1512 };
1400 };
1513
1401
1514 // DataScheme for owner
1402 // DataScheme for owner
1515 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1403 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1516
1404
1517 ownerDS.responseSchema = {
1405 ownerDS.responseSchema = {
1518 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1406 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1519 };
1407 };
1520
1408
1521 // Instantiate AutoComplete for mentions
1409 // Instantiate AutoComplete for mentions
1522 var ownerAC = new YAHOO.widget.AutoComplete(divid, cont, ownerDS);
1410 var ownerAC = new YAHOO.widget.AutoComplete(divid, cont, ownerDS);
1523 ownerAC.useShadow = false;
1411 ownerAC.useShadow = false;
1524 ownerAC.resultTypeList = false;
1412 ownerAC.resultTypeList = false;
1525 ownerAC.suppressInputUpdate = true;
1413 ownerAC.suppressInputUpdate = true;
1526 ownerAC.animVert = false;
1414 ownerAC.animVert = false;
1527 ownerAC.animHoriz = false;
1415 ownerAC.animHoriz = false;
1528 ownerAC.animSpeed = 0.1;
1416 ownerAC.animSpeed = 0.1;
1529
1417
1530 // Helper highlight function for the formatter
1418 // Helper highlight function for the formatter
1531 var highlightMatch = function (full, snippet, matchindex) {
1419 var highlightMatch = function (full, snippet, matchindex) {
1532 return full.substring(0, matchindex)
1420 return full.substring(0, matchindex)
1533 + "<span class='match'>"
1421 + "<span class='match'>"
1534 + full.substr(matchindex, snippet.length)
1422 + full.substr(matchindex, snippet.length)
1535 + "</span>" + full.substring(matchindex + snippet.length);
1423 + "</span>" + full.substring(matchindex + snippet.length);
1536 };
1424 };
1537
1425
1538 // Custom formatter to highlight the matching letters
1426 // Custom formatter to highlight the matching letters
1539 ownerAC.formatResult = function (oResultData, sQuery, sResultMatch) {
1427 ownerAC.formatResult = function (oResultData, sQuery, sResultMatch) {
1540 var org_sQuery = sQuery;
1428 var org_sQuery = sQuery;
1541 if(this.dataSource.mentionQuery != null){
1429 if(this.dataSource.mentionQuery != null){
1542 sQuery = this.dataSource.mentionQuery;
1430 sQuery = this.dataSource.mentionQuery;
1543 }
1431 }
1544
1432
1545 var query = sQuery.toLowerCase();
1433 var query = sQuery.toLowerCase();
1546 var _gravatar = function(res, em, group){
1434 var _gravatar = function(res, em, group){
1547 if (group !== undefined){
1435 if (group !== undefined){
1548 em = '/images/icons/group.png'
1436 em = '/images/icons/group.png'
1549 }
1437 }
1550 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1438 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1551 return tmpl.format(em,res)
1439 return tmpl.format(em,res)
1552 }
1440 }
1553 if (oResultData.nname != undefined) {
1441 if (oResultData.nname != undefined) {
1554 var fname = oResultData.fname || "";
1442 var fname = oResultData.fname || "";
1555 var lname = oResultData.lname || "";
1443 var lname = oResultData.lname || "";
1556 var nname = oResultData.nname;
1444 var nname = oResultData.nname;
1557
1445
1558 // Guard against null value
1446 // Guard against null value
1559 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1447 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1560 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1448 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1561 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1449 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1562 displayfname, displaylname, displaynname;
1450 displayfname, displaylname, displaynname;
1563
1451
1564 if (fnameMatchIndex > -1) {
1452 if (fnameMatchIndex > -1) {
1565 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1453 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1566 } else {
1454 } else {
1567 displayfname = fname;
1455 displayfname = fname;
1568 }
1456 }
1569
1457
1570 if (lnameMatchIndex > -1) {
1458 if (lnameMatchIndex > -1) {
1571 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1459 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1572 } else {
1460 } else {
1573 displaylname = lname;
1461 displaylname = lname;
1574 }
1462 }
1575
1463
1576 if (nnameMatchIndex > -1) {
1464 if (nnameMatchIndex > -1) {
1577 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1465 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1578 } else {
1466 } else {
1579 displaynname = nname ? "(" + nname + ")" : "";
1467 displaynname = nname ? "(" + nname + ")" : "";
1580 }
1468 }
1581
1469
1582 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1470 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1583 } else {
1471 } else {
1584 return '';
1472 return '';
1585 }
1473 }
1586 };
1474 };
1587
1475
1588 if(ownerAC.itemSelectEvent){
1476 if(ownerAC.itemSelectEvent){
1589 ownerAC.itemSelectEvent.subscribe(function (sType, aArgs) {
1477 ownerAC.itemSelectEvent.subscribe(function (sType, aArgs) {
1590
1478
1591 var myAC = aArgs[0]; // reference back to the AC instance
1479 var myAC = aArgs[0]; // reference back to the AC instance
1592 var elLI = aArgs[1]; // reference to the selected LI element
1480 var elLI = aArgs[1]; // reference to the selected LI element
1593 var oData = aArgs[2]; // object literal of selected item's result data
1481 var oData = aArgs[2]; // object literal of selected item's result data
1594 //fill the autocomplete with value
1482 //fill the autocomplete with value
1595 if (oData.nname != undefined) {
1483 if (oData.nname != undefined) {
1596 //users
1484 //users
1597 //Replace the mention name with replaced
1485 //Replace the mention name with replaced
1598 var re = new RegExp();
1486 var re = new RegExp();
1599 var org = myAC.getInputEl().value;
1487 var org = myAC.getInputEl().value;
1600 var chunks = myAC.dataSource.chunks
1488 var chunks = myAC.dataSource.chunks
1601 // replace middle chunk(the search term) with actuall match
1489 // replace middle chunk(the search term) with actuall match
1602 chunks[1] = chunks[1].replace('@'+myAC.dataSource.mentionQuery,
1490 chunks[1] = chunks[1].replace('@'+myAC.dataSource.mentionQuery,
1603 '@'+oData.nname+' ');
1491 '@'+oData.nname+' ');
1604 myAC.getInputEl().value = chunks.join('')
1492 myAC.getInputEl().value = chunks.join('')
1605 YUD.get(myAC.getInputEl()).focus(); // Y U NO WORK !?
1493 YUD.get(myAC.getInputEl()).focus(); // Y U NO WORK !?
1606 } else {
1494 } else {
1607 //groups
1495 //groups
1608 myAC.getInputEl().value = oData.grname;
1496 myAC.getInputEl().value = oData.grname;
1609 YUD.get('perm_new_member_type').value = 'users_group';
1497 YUD.get('perm_new_member_type').value = 'users_group';
1610 }
1498 }
1611 });
1499 });
1612 }
1500 }
1613
1501
1614 // in this keybuffer we will gather current value of search !
1502 // in this keybuffer we will gather current value of search !
1615 // since we need to get this just when someone does `@` then we do the
1503 // since we need to get this just when someone does `@` then we do the
1616 // search
1504 // search
1617 ownerAC.dataSource.chunks = [];
1505 ownerAC.dataSource.chunks = [];
1618 ownerAC.dataSource.mentionQuery = null;
1506 ownerAC.dataSource.mentionQuery = null;
1619
1507
1620 ownerAC.get_mention = function(msg, max_pos) {
1508 ownerAC.get_mention = function(msg, max_pos) {
1621 var org = msg;
1509 var org = msg;
1622 var re = new RegExp('(?:^@|\s@)([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)$')
1510 var re = new RegExp('(?:^@|\s@)([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)$')
1623 var chunks = [];
1511 var chunks = [];
1624
1512
1625
1626 // cut first chunk until curret pos
1513 // cut first chunk until curret pos
1627 var to_max = msg.substr(0, max_pos);
1514 var to_max = msg.substr(0, max_pos);
1628 var at_pos = Math.max(0,to_max.lastIndexOf('@')-1);
1515 var at_pos = Math.max(0,to_max.lastIndexOf('@')-1);
1629 var msg2 = to_max.substr(at_pos);
1516 var msg2 = to_max.substr(at_pos);
1630
1517
1631 chunks.push(org.substr(0,at_pos))// prefix chunk
1518 chunks.push(org.substr(0,at_pos))// prefix chunk
1632 chunks.push(msg2) // search chunk
1519 chunks.push(msg2) // search chunk
1633 chunks.push(org.substr(max_pos)) // postfix chunk
1520 chunks.push(org.substr(max_pos)) // postfix chunk
1634
1521
1635 // clean up msg2 for filtering and regex match
1522 // clean up msg2 for filtering and regex match
1636 var msg2 = msg2.lstrip(' ').lstrip('\n');
1523 var msg2 = msg2.lstrip(' ').lstrip('\n');
1637
1524
1638 if(re.test(msg2)){
1525 if(re.test(msg2)){
1639 var unam = re.exec(msg2)[1];
1526 var unam = re.exec(msg2)[1];
1640 return [unam, chunks];
1527 return [unam, chunks];
1641 }
1528 }
1642 return [null, null];
1529 return [null, null];
1643 };
1530 };
1644
1531
1645 if (ownerAC.textboxKeyUpEvent){
1532 if (ownerAC.textboxKeyUpEvent){
1646 ownerAC.textboxKeyUpEvent.subscribe(function(type, args){
1533 ownerAC.textboxKeyUpEvent.subscribe(function(type, args){
1647
1534
1648 var ac_obj = args[0];
1535 var ac_obj = args[0];
1649 var currentMessage = args[1];
1536 var currentMessage = args[1];
1650 var currentCaretPosition = args[0]._elTextbox.selectionStart;
1537 var currentCaretPosition = args[0]._elTextbox.selectionStart;
1651
1538
1652 var unam = ownerAC.get_mention(currentMessage, currentCaretPosition);
1539 var unam = ownerAC.get_mention(currentMessage, currentCaretPosition);
1653 var curr_search = null;
1540 var curr_search = null;
1654 if(unam[0]){
1541 if(unam[0]){
1655 curr_search = unam[0];
1542 curr_search = unam[0];
1656 }
1543 }
1657
1544
1658 ownerAC.dataSource.chunks = unam[1];
1545 ownerAC.dataSource.chunks = unam[1];
1659 ownerAC.dataSource.mentionQuery = curr_search;
1546 ownerAC.dataSource.mentionQuery = curr_search;
1660
1547
1661 })
1548 })
1662 }
1549 }
1663 return {
1550 return {
1664 ownerDS: ownerDS,
1551 ownerDS: ownerDS,
1665 ownerAC: ownerAC,
1552 ownerAC: ownerAC,
1666 };
1553 };
1667 }
1554 }
1668
1555
1669 var addReviewMember = function(id,fname,lname,nname,gravatar_link){
1556 var addReviewMember = function(id,fname,lname,nname,gravatar_link){
1670 var members = YUD.get('review_members');
1557 var members = YUD.get('review_members');
1671 var tmpl = '<li id="reviewer_{2}">'+
1558 var tmpl = '<li id="reviewer_{2}">'+
1672 '<div class="reviewers_member">'+
1559 '<div class="reviewers_member">'+
1673 '<div class="gravatar"><img alt="gravatar" src="{0}"/> </div>'+
1560 '<div class="gravatar"><img alt="gravatar" src="{0}"/> </div>'+
1674 '<div style="float:left">{1}</div>'+
1561 '<div style="float:left">{1}</div>'+
1675 '<input type="hidden" value="{2}" name="review_members" />'+
1562 '<input type="hidden" value="{2}" name="review_members" />'+
1676 '<span class="delete_icon action_button" onclick="removeReviewMember({2})"></span>'+
1563 '<span class="delete_icon action_button" onclick="removeReviewMember({2})"></span>'+
1677 '</div>'+
1564 '</div>'+
1678 '</li>' ;
1565 '</li>' ;
1679 var displayname = "{0} {1} ({2})".format(fname,lname,nname);
1566 var displayname = "{0} {1} ({2})".format(fname,lname,nname);
1680 var element = tmpl.format(gravatar_link,displayname,id);
1567 var element = tmpl.format(gravatar_link,displayname,id);
1681 // check if we don't have this ID already in
1568 // check if we don't have this ID already in
1682 var ids = [];
1569 var ids = [];
1683 var _els = YUQ('#review_members li');
1570 var _els = YUQ('#review_members li');
1684 for (el in _els){
1571 for (el in _els){
1685 ids.push(_els[el].id)
1572 ids.push(_els[el].id)
1686 }
1573 }
1687 if(ids.indexOf('reviewer_'+id) == -1){
1574 if(ids.indexOf('reviewer_'+id) == -1){
1688 //only add if it's not there
1575 //only add if it's not there
1689 members.innerHTML += element;
1576 members.innerHTML += element;
1690 }
1577 }
1691
1692 }
1578 }
1693
1579
1694 var removeReviewMember = function(reviewer_id, repo_name, pull_request_id){
1580 var removeReviewMember = function(reviewer_id, repo_name, pull_request_id){
1695 var el = YUD.get('reviewer_{0}'.format(reviewer_id));
1581 var el = YUD.get('reviewer_{0}'.format(reviewer_id));
1696 if (el.parentNode !== undefined){
1582 if (el.parentNode !== undefined){
1697 el.parentNode.removeChild(el);
1583 el.parentNode.removeChild(el);
1698 }
1584 }
1699 }
1585 }
1700
1586
1701 var updateReviewers = function(reviewers_ids, repo_name, pull_request_id){
1587 var updateReviewers = function(reviewers_ids, repo_name, pull_request_id){
1702 if (reviewers_ids === undefined){
1588 if (reviewers_ids === undefined){
1703 var reviewers_ids = [];
1589 var reviewers_ids = [];
1704 var ids = YUQ('#review_members input');
1590 var ids = YUQ('#review_members input');
1705 for(var i=0; i<ids.length;i++){
1591 for(var i=0; i<ids.length;i++){
1706 var id = ids[i].value
1592 var id = ids[i].value
1707 reviewers_ids.push(id);
1593 reviewers_ids.push(id);
1708 }
1594 }
1709 }
1595 }
1710 var url = pyroutes.url('pullrequest_update', {"repo_name":repo_name,
1596 var url = pyroutes.url('pullrequest_update', {"repo_name":repo_name,
1711 "pull_request_id": pull_request_id});
1597 "pull_request_id": pull_request_id});
1712 var postData = {'_method':'put',
1598 var postData = {'_method':'put',
1713 'reviewers_ids': reviewers_ids};
1599 'reviewers_ids': reviewers_ids};
1714 var success = function(o){
1600 var success = function(o){
1715 window.location.reload();
1601 window.location.reload();
1716 }
1602 }
1717 ajaxPOST(url,postData,success);
1603 ajaxPOST(url,postData,success);
1718 }
1604 }
1719
1605
1720 var PullRequestAutoComplete = function (divid, cont, users_list, groups_list) {
1606 var PullRequestAutoComplete = function (divid, cont, users_list, groups_list) {
1721 var myUsers = users_list;
1607 var myUsers = users_list;
1722 var myGroups = groups_list;
1608 var myGroups = groups_list;
1723
1609
1724 // Define a custom search function for the DataSource of users
1610 // Define a custom search function for the DataSource of users
1725 var matchUsers = function (sQuery) {
1611 var matchUsers = function (sQuery) {
1726 // Case insensitive matching
1612 // Case insensitive matching
1727 var query = sQuery.toLowerCase();
1613 var query = sQuery.toLowerCase();
1728 var i = 0;
1614 var i = 0;
1729 var l = myUsers.length;
1615 var l = myUsers.length;
1730 var matches = [];
1616 var matches = [];
1731
1617
1732 // Match against each name of each contact
1618 // Match against each name of each contact
1733 for (; i < l; i++) {
1619 for (; i < l; i++) {
1734 contact = myUsers[i];
1620 contact = myUsers[i];
1735 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1621 if (((contact.fname+"").toLowerCase().indexOf(query) > -1) ||
1736 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1622 ((contact.lname+"").toLowerCase().indexOf(query) > -1) ||
1737 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1623 ((contact.nname) && ((contact.nname).toLowerCase().indexOf(query) > -1))) {
1738 matches[matches.length] = contact;
1624 matches[matches.length] = contact;
1739 }
1625 }
1740 }
1626 }
1741 return matches;
1627 return matches;
1742 };
1628 };
1743
1629
1744 // Define a custom search function for the DataSource of userGroups
1630 // Define a custom search function for the DataSource of userGroups
1745 var matchGroups = function (sQuery) {
1631 var matchGroups = function (sQuery) {
1746 // Case insensitive matching
1632 // Case insensitive matching
1747 var query = sQuery.toLowerCase();
1633 var query = sQuery.toLowerCase();
1748 var i = 0;
1634 var i = 0;
1749 var l = myGroups.length;
1635 var l = myGroups.length;
1750 var matches = [];
1636 var matches = [];
1751
1637
1752 // Match against each name of each contact
1638 // Match against each name of each contact
1753 for (; i < l; i++) {
1639 for (; i < l; i++) {
1754 matched_group = myGroups[i];
1640 matched_group = myGroups[i];
1755 if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
1641 if (matched_group.grname.toLowerCase().indexOf(query) > -1) {
1756 matches[matches.length] = matched_group;
1642 matches[matches.length] = matched_group;
1757 }
1643 }
1758 }
1644 }
1759 return matches;
1645 return matches;
1760 };
1646 };
1761
1647
1762 //match all
1648 //match all
1763 var matchAll = function (sQuery) {
1649 var matchAll = function (sQuery) {
1764 u = matchUsers(sQuery);
1650 u = matchUsers(sQuery);
1765 return u
1651 return u
1766 };
1652 };
1767
1653
1768 // DataScheme for owner
1654 // DataScheme for owner
1769 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1655 var ownerDS = new YAHOO.util.FunctionDataSource(matchUsers);
1770
1656
1771 ownerDS.responseSchema = {
1657 ownerDS.responseSchema = {
1772 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1658 fields: ["id", "fname", "lname", "nname", "gravatar_lnk"]
1773 };
1659 };
1774
1660
1775 // Instantiate AutoComplete for mentions
1661 // Instantiate AutoComplete for mentions
1776 var reviewerAC = new YAHOO.widget.AutoComplete(divid, cont, ownerDS);
1662 var reviewerAC = new YAHOO.widget.AutoComplete(divid, cont, ownerDS);
1777 reviewerAC.useShadow = false;
1663 reviewerAC.useShadow = false;
1778 reviewerAC.resultTypeList = false;
1664 reviewerAC.resultTypeList = false;
1779 reviewerAC.suppressInputUpdate = true;
1665 reviewerAC.suppressInputUpdate = true;
1780 reviewerAC.animVert = false;
1666 reviewerAC.animVert = false;
1781 reviewerAC.animHoriz = false;
1667 reviewerAC.animHoriz = false;
1782 reviewerAC.animSpeed = 0.1;
1668 reviewerAC.animSpeed = 0.1;
1783
1669
1784 // Helper highlight function for the formatter
1670 // Helper highlight function for the formatter
1785 var highlightMatch = function (full, snippet, matchindex) {
1671 var highlightMatch = function (full, snippet, matchindex) {
1786 return full.substring(0, matchindex)
1672 return full.substring(0, matchindex)
1787 + "<span class='match'>"
1673 + "<span class='match'>"
1788 + full.substr(matchindex, snippet.length)
1674 + full.substr(matchindex, snippet.length)
1789 + "</span>" + full.substring(matchindex + snippet.length);
1675 + "</span>" + full.substring(matchindex + snippet.length);
1790 };
1676 };
1791
1677
1792 // Custom formatter to highlight the matching letters
1678 // Custom formatter to highlight the matching letters
1793 reviewerAC.formatResult = function (oResultData, sQuery, sResultMatch) {
1679 reviewerAC.formatResult = function (oResultData, sQuery, sResultMatch) {
1794 var org_sQuery = sQuery;
1680 var org_sQuery = sQuery;
1795 if(this.dataSource.mentionQuery != null){
1681 if(this.dataSource.mentionQuery != null){
1796 sQuery = this.dataSource.mentionQuery;
1682 sQuery = this.dataSource.mentionQuery;
1797 }
1683 }
1798
1684
1799 var query = sQuery.toLowerCase();
1685 var query = sQuery.toLowerCase();
1800 var _gravatar = function(res, em, group){
1686 var _gravatar = function(res, em, group){
1801 if (group !== undefined){
1687 if (group !== undefined){
1802 em = '/images/icons/group.png'
1688 em = '/images/icons/group.png'
1803 }
1689 }
1804 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1690 tmpl = '<div class="ac-container-wrap"><img class="perm-gravatar-ac" src="{0}"/>{1}</div>'
1805 return tmpl.format(em,res)
1691 return tmpl.format(em,res)
1806 }
1692 }
1807 if (oResultData.nname != undefined) {
1693 if (oResultData.nname != undefined) {
1808 var fname = oResultData.fname || "";
1694 var fname = oResultData.fname || "";
1809 var lname = oResultData.lname || "";
1695 var lname = oResultData.lname || "";
1810 var nname = oResultData.nname;
1696 var nname = oResultData.nname;
1811
1697
1812 // Guard against null value
1698 // Guard against null value
1813 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1699 var fnameMatchIndex = fname.toLowerCase().indexOf(query),
1814 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1700 lnameMatchIndex = lname.toLowerCase().indexOf(query),
1815 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1701 nnameMatchIndex = nname.toLowerCase().indexOf(query),
1816 displayfname, displaylname, displaynname;
1702 displayfname, displaylname, displaynname;
1817
1703
1818 if (fnameMatchIndex > -1) {
1704 if (fnameMatchIndex > -1) {
1819 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1705 displayfname = highlightMatch(fname, query, fnameMatchIndex);
1820 } else {
1706 } else {
1821 displayfname = fname;
1707 displayfname = fname;
1822 }
1708 }
1823
1709
1824 if (lnameMatchIndex > -1) {
1710 if (lnameMatchIndex > -1) {
1825 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1711 displaylname = highlightMatch(lname, query, lnameMatchIndex);
1826 } else {
1712 } else {
1827 displaylname = lname;
1713 displaylname = lname;
1828 }
1714 }
1829
1715
1830 if (nnameMatchIndex > -1) {
1716 if (nnameMatchIndex > -1) {
1831 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1717 displaynname = "(" + highlightMatch(nname, query, nnameMatchIndex) + ")";
1832 } else {
1718 } else {
1833 displaynname = nname ? "(" + nname + ")" : "";
1719 displaynname = nname ? "(" + nname + ")" : "";
1834 }
1720 }
1835
1721
1836 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1722 return _gravatar(displayfname + " " + displaylname + " " + displaynname, oResultData.gravatar_lnk);
1837 } else {
1723 } else {
1838 return '';
1724 return '';
1839 }
1725 }
1840 };
1726 };
1841
1727
1842 //members cache to catch duplicates
1728 //members cache to catch duplicates
1843 reviewerAC.dataSource.cache = [];
1729 reviewerAC.dataSource.cache = [];
1844 // hack into select event
1730 // hack into select event
1845 if(reviewerAC.itemSelectEvent){
1731 if(reviewerAC.itemSelectEvent){
1846 reviewerAC.itemSelectEvent.subscribe(function (sType, aArgs) {
1732 reviewerAC.itemSelectEvent.subscribe(function (sType, aArgs) {
1847
1733
1848 var myAC = aArgs[0]; // reference back to the AC instance
1734 var myAC = aArgs[0]; // reference back to the AC instance
1849 var elLI = aArgs[1]; // reference to the selected LI element
1735 var elLI = aArgs[1]; // reference to the selected LI element
1850 var oData = aArgs[2]; // object literal of selected item's result data
1736 var oData = aArgs[2]; // object literal of selected item's result data
1851
1737
1852 //fill the autocomplete with value
1738 //fill the autocomplete with value
1853
1739
1854 if (oData.nname != undefined) {
1740 if (oData.nname != undefined) {
1855 addReviewMember(oData.id, oData.fname, oData.lname, oData.nname,
1741 addReviewMember(oData.id, oData.fname, oData.lname, oData.nname,
1856 oData.gravatar_lnk);
1742 oData.gravatar_lnk);
1857 myAC.dataSource.cache.push(oData.id);
1743 myAC.dataSource.cache.push(oData.id);
1858 YUD.get('user').value = ''
1744 YUD.get('user').value = ''
1859 }
1745 }
1860 });
1746 });
1861 }
1747 }
1862 return {
1748 return {
1863 ownerDS: ownerDS,
1749 ownerDS: ownerDS,
1864 reviewerAC: reviewerAC,
1750 reviewerAC: reviewerAC,
1865 };
1751 };
1866 }
1752 }
1867
1753
1868 /**
1754 /**
1869 * QUICK REPO MENU
1755 * QUICK REPO MENU
1870 */
1756 */
1871 var quick_repo_menu = function(){
1757 var quick_repo_menu = function(){
1872 YUE.on(YUQ('.quick_repo_menu'),'mouseenter',function(e){
1758 YUE.on(YUQ('.quick_repo_menu'),'mouseenter',function(e){
1873 var menu = e.currentTarget.firstElementChild.firstElementChild;
1759 var menu = e.currentTarget.firstElementChild.firstElementChild;
1874 if(YUD.hasClass(menu,'hidden')){
1760 if(YUD.hasClass(menu,'hidden')){
1875 YUD.replaceClass(e.currentTarget,'hidden', 'active');
1761 YUD.replaceClass(e.currentTarget,'hidden', 'active');
1876 YUD.replaceClass(menu, 'hidden', 'active');
1762 YUD.replaceClass(menu, 'hidden', 'active');
1877 }
1763 }
1878 })
1764 })
1879 YUE.on(YUQ('.quick_repo_menu'),'mouseleave',function(e){
1765 YUE.on(YUQ('.quick_repo_menu'),'mouseleave',function(e){
1880 var menu = e.currentTarget.firstElementChild.firstElementChild;
1766 var menu = e.currentTarget.firstElementChild.firstElementChild;
1881 if(YUD.hasClass(menu,'active')){
1767 if(YUD.hasClass(menu,'active')){
1882 YUD.replaceClass(e.currentTarget, 'active', 'hidden');
1768 YUD.replaceClass(e.currentTarget, 'active', 'hidden');
1883 YUD.replaceClass(menu, 'active', 'hidden');
1769 YUD.replaceClass(menu, 'active', 'hidden');
1884 }
1770 }
1885 })
1771 })
1886 };
1772 };
1887
1773
1888
1774
1889 /**
1775 /**
1890 * TABLE SORTING
1776 * TABLE SORTING
1891 */
1777 */
1892
1778
1893 // returns a node from given html;
1779 // returns a node from given html;
1894 var fromHTML = function(html){
1780 var fromHTML = function(html){
1895 var _html = document.createElement('element');
1781 var _html = document.createElement('element');
1896 _html.innerHTML = html;
1782 _html.innerHTML = html;
1897 return _html;
1783 return _html;
1898 }
1784 }
1785
1899 var get_rev = function(node){
1786 var get_rev = function(node){
1900 var n = node.firstElementChild.firstElementChild;
1787 var n = node.firstElementChild.firstElementChild;
1901
1788
1902 if (n===null){
1789 if (n===null){
1903 return -1
1790 return -1
1904 }
1791 }
1905 else{
1792 else{
1906 out = n.firstElementChild.innerHTML.split(':')[0].replace('r','');
1793 out = n.firstElementChild.innerHTML.split(':')[0].replace('r','');
1907 return parseInt(out);
1794 return parseInt(out);
1908 }
1795 }
1909 }
1796 }
1910
1797
1911 var get_name = function(node){
1912 var name = node.firstElementChild.children[2].innerHTML;
1913 return name
1914 }
1915 var get_group_name = function(node){
1916 var name = node.firstElementChild.children[1].innerHTML;
1917 return name
1918 }
1919 var get_date = function(node){
1798 var get_date = function(node){
1920 var date_ = YUD.getAttribute(node.firstElementChild,'date');
1799 var date_ = YUD.getAttribute(node.firstElementChild,'date');
1921 return date_
1800 return date_
1922 }
1801 }
1923
1802
1924 var get_age = function(node){
1925 return node
1926 }
1927
1928 var get_link = function(node){
1929 return node.firstElementChild.text;
1930 }
1931
1932 var revisionSort = function(a, b, desc, field) {
1803 var revisionSort = function(a, b, desc, field) {
1933
1934 var a_ = fromHTML(a.getData(field));
1804 var a_ = fromHTML(a.getData(field));
1935 var b_ = fromHTML(b.getData(field));
1805 var b_ = fromHTML(b.getData(field));
1936
1806
1937 // extract revisions from string nodes
1807 // extract revisions from string nodes
1938 a_ = get_rev(a_)
1808 a_ = get_rev(a_)
1939 b_ = get_rev(b_)
1809 b_ = get_rev(b_)
1940
1810
1941 var comp = YAHOO.util.Sort.compare;
1811 var comp = YAHOO.util.Sort.compare;
1942 var compState = comp(a_, b_, desc);
1812 var compState = comp(a_, b_, desc);
1943 return compState;
1813 return compState;
1944 };
1814 };
1815
1945 var ageSort = function(a, b, desc, field) {
1816 var ageSort = function(a, b, desc, field) {
1946 var a_ = fromHTML(a.getData(field));
1817 var a_ = fromHTML(a.getData(field));
1947 var b_ = fromHTML(b.getData(field));
1818 var b_ = fromHTML(b.getData(field));
1948
1819
1949 // extract name from table
1820 // extract name from table
1950 a_ = get_date(a_)
1821 a_ = get_date(a_)
1951 b_ = get_date(b_)
1822 b_ = get_date(b_)
1952
1823
1953 var comp = YAHOO.util.Sort.compare;
1824 var comp = YAHOO.util.Sort.compare;
1954 var compState = comp(a_, b_, desc);
1825 var compState = comp(a_, b_, desc);
1955 return compState;
1826 return compState;
1956 };
1827 };
1957
1828
1958 var lastLoginSort = function(a, b, desc, field) {
1829 var lastLoginSort = function(a, b, desc, field) {
1959 var a_ = a.getData('last_login_raw') || 0;
1830 var a_ = a.getData('last_login_raw') || 0;
1960 var b_ = b.getData('last_login_raw') || 0;
1831 var b_ = b.getData('last_login_raw') || 0;
1961
1832
1962 var comp = YAHOO.util.Sort.compare;
1833 var comp = YAHOO.util.Sort.compare;
1963 var compState = comp(a_, b_, desc);
1834 var compState = comp(a_, b_, desc);
1964 return compState;
1835 return compState;
1965 };
1836 };
1966
1837
1967 var nameSort = function(a, b, desc, field) {
1838 var nameSort = function(a, b, desc, field) {
1968 var a_ = a.getData('raw_name') || 0;
1839 var a_ = a.getData('raw_name') || 0;
1969 var b_ = b.getData('raw_name') || 0;
1840 var b_ = b.getData('raw_name') || 0;
1970
1841
1971 var comp = YAHOO.util.Sort.compare;
1842 var comp = YAHOO.util.Sort.compare;
1972 var compState = comp(a_, b_, desc);
1843 var compState = comp(a_, b_, desc);
1973 return compState;
1844 return compState;
1974 };
1845 };
1975
1846
1976 var permNameSort = function(a, b, desc, field) {
1977 var a_ = fromHTML(a.getData(field));
1978 var b_ = fromHTML(b.getData(field));
1979 // extract name from table
1980
1981 a_ = a_.children[0].innerHTML;
1982 b_ = b_.children[0].innerHTML;
1983
1984 var comp = YAHOO.util.Sort.compare;
1985 var compState = comp(a_, b_, desc);
1986 return compState;
1987 };
1988
1989 var groupNameSort = function(a, b, desc, field) {
1990 var a_ = fromHTML(a.getData(field));
1991 var b_ = fromHTML(b.getData(field));
1992
1993 // extract name from table
1994 a_ = get_group_name(a_)
1995 b_ = get_group_name(b_)
1996
1997 var comp = YAHOO.util.Sort.compare;
1998 var compState = comp(a_, b_, desc);
1999 return compState;
2000 };
2001 var dateSort = function(a, b, desc, field) {
1847 var dateSort = function(a, b, desc, field) {
2002 var a_ = fromHTML(a.getData(field));
1848 var a_ = fromHTML(a.getData(field));
2003 var b_ = fromHTML(b.getData(field));
1849 var b_ = fromHTML(b.getData(field));
2004
1850
2005 // extract name from table
1851 // extract name from table
2006 a_ = get_date(a_)
1852 a_ = get_date(a_)
2007 b_ = get_date(b_)
1853 b_ = get_date(b_)
2008
1854
2009 var comp = YAHOO.util.Sort.compare;
1855 var comp = YAHOO.util.Sort.compare;
2010 var compState = comp(a_, b_, desc);
1856 var compState = comp(a_, b_, desc);
2011 return compState;
1857 return compState;
2012 };
1858 };
2013
1859
2014 var usernamelinkSort = function(a, b, desc, field) {
2015 var a_ = fromHTML(a.getData(field));
2016 var b_ = fromHTML(b.getData(field));
2017
2018 // extract url text from string nodes
2019 a_ = get_link(a_)
2020 b_ = get_link(b_)
2021 var comp = YAHOO.util.Sort.compare;
2022 var compState = comp(a_, b_, desc);
2023 return compState;
2024 }
2025
2026 var addPermAction = function(_html, users_list, groups_list){
1860 var addPermAction = function(_html, users_list, groups_list){
2027 var elmts = YUD.getElementsByClassName('last_new_member');
1861 var elmts = YUD.getElementsByClassName('last_new_member');
2028 var last_node = elmts[elmts.length-1];
1862 var last_node = elmts[elmts.length-1];
2029 if (last_node){
1863 if (last_node){
2030 var next_id = (YUD.getElementsByClassName('new_members')).length;
1864 var next_id = (YUD.getElementsByClassName('new_members')).length;
2031 _html = _html.format(next_id);
1865 _html = _html.format(next_id);
2032 last_node.innerHTML = _html;
1866 last_node.innerHTML = _html;
2033 YUD.setStyle(last_node, 'display', '');
1867 YUD.setStyle(last_node, 'display', '');
2034 YUD.removeClass(last_node, 'last_new_member');
1868 YUD.removeClass(last_node, 'last_new_member');
2035 MembersAutoComplete("perm_new_member_name_"+next_id,
1869 MembersAutoComplete("perm_new_member_name_"+next_id,
2036 "perm_container_"+next_id, users_list, groups_list);
1870 "perm_container_"+next_id, users_list, groups_list);
2037 //create new last NODE
1871 //create new last NODE
2038 var el = document.createElement('tr');
1872 var el = document.createElement('tr');
2039 el.id = 'add_perm_input';
1873 el.id = 'add_perm_input';
2040 YUD.addClass(el,'last_new_member');
1874 YUD.addClass(el,'last_new_member');
2041 YUD.addClass(el,'new_members');
1875 YUD.addClass(el,'new_members');
2042 YUD.insertAfter(el, last_node);
1876 YUD.insertAfter(el, last_node);
2043 }
1877 }
2044 }
1878 }
1879
2045 function ajaxActionRevokePermission(url, obj_id, obj_type, field_id, extra_data) {
1880 function ajaxActionRevokePermission(url, obj_id, obj_type, field_id, extra_data) {
2046 var callback = {
1881 var callback = {
2047 success: function (o) {
1882 success: function (o) {
2048 var tr = YUD.get(String(field_id));
1883 var tr = YUD.get(String(field_id));
2049 tr.parentNode.removeChild(tr);
1884 tr.parentNode.removeChild(tr);
2050 },
1885 },
2051 failure: function (o) {
1886 failure: function (o) {
2052 alert(_TM['Failed to remoke permission'] + ": " + o.status);
1887 alert(_TM['Failed to remoke permission'] + ": " + o.status);
2053 },
1888 },
2054 };
1889 };
2055 query_params = {
1890 query_params = {
2056 '_method': 'delete'
1891 '_method': 'delete'
2057 }
1892 }
2058 // put extra data into POST
1893 // put extra data into POST
2059 if (extra_data !== undefined && (typeof extra_data === 'object')){
1894 if (extra_data !== undefined && (typeof extra_data === 'object')){
2060 for(k in extra_data){
1895 for(k in extra_data){
2061 query_params[k] = extra_data[k];
1896 query_params[k] = extra_data[k];
2062 }
1897 }
2063 }
1898 }
2064
1899
2065 if (obj_type=='user'){
1900 if (obj_type=='user'){
2066 query_params['user_id'] = obj_id;
1901 query_params['user_id'] = obj_id;
2067 query_params['obj_type'] = 'user';
1902 query_params['obj_type'] = 'user';
2068 }
1903 }
2069 else if (obj_type=='user_group'){
1904 else if (obj_type=='user_group'){
2070 query_params['user_group_id'] = obj_id;
1905 query_params['user_group_id'] = obj_id;
2071 query_params['obj_type'] = 'user_group';
1906 query_params['obj_type'] = 'user_group';
2072 }
1907 }
2073
1908
2074 var request = YAHOO.util.Connect.asyncRequest('POST', url, callback,
1909 var request = YAHOO.util.Connect.asyncRequest('POST', url, callback,
2075 toQueryString(query_params));
1910 toQueryString(query_params));
2076 };
1911 };
1912
2077 /* Multi selectors */
1913 /* Multi selectors */
2078
1914
2079 var MultiSelectWidget = function(selected_id, available_id, form_id){
1915 var MultiSelectWidget = function(selected_id, available_id, form_id){
2080
2081
2082 //definition of containers ID's
1916 //definition of containers ID's
2083 var selected_container = selected_id;
1917 var selected_container = selected_id;
2084 var available_container = available_id;
1918 var available_container = available_id;
2085
1919
2086 //temp container for selected storage.
1920 //temp container for selected storage.
2087 var cache = new Array();
1921 var cache = new Array();
2088 var av_cache = new Array();
1922 var av_cache = new Array();
2089 var c = YUD.get(selected_container);
1923 var c = YUD.get(selected_container);
2090 var ac = YUD.get(available_container);
1924 var ac = YUD.get(available_container);
2091
1925
2092 //get only selected options for further fullfilment
1926 //get only selected options for further fullfilment
2093 for(var i = 0;node =c.options[i];i++){
1927 for(var i = 0;node =c.options[i];i++){
2094 if(node.selected){
1928 if(node.selected){
2095 //push selected to my temp storage left overs :)
1929 //push selected to my temp storage left overs :)
2096 cache.push(node);
1930 cache.push(node);
2097 }
1931 }
2098 }
1932 }
2099
1933
2100 //get all available options to cache
1934 //get all available options to cache
2101 for(var i = 0;node =ac.options[i];i++){
1935 for(var i = 0;node =ac.options[i];i++){
2102 //push selected to my temp storage left overs :)
1936 //push selected to my temp storage left overs :)
2103 av_cache.push(node);
1937 av_cache.push(node);
2104 }
1938 }
2105
1939
2106 //fill available only with those not in chosen
1940 //fill available only with those not in chosen
2107 ac.options.length=0;
1941 ac.options.length=0;
2108 tmp_cache = new Array();
1942 tmp_cache = new Array();
2109
1943
2110 for(var i = 0;node = av_cache[i];i++){
1944 for(var i = 0;node = av_cache[i];i++){
2111 var add = true;
1945 var add = true;
2112 for(var i2 = 0;node_2 = cache[i2];i2++){
1946 for(var i2 = 0;node_2 = cache[i2];i2++){
2113 if(node.value == node_2.value){
1947 if(node.value == node_2.value){
2114 add=false;
1948 add=false;
2115 break;
1949 break;
2116 }
1950 }
2117 }
1951 }
2118 if(add){
1952 if(add){
2119 tmp_cache.push(new Option(node.text, node.value, false, false));
1953 tmp_cache.push(new Option(node.text, node.value, false, false));
2120 }
1954 }
2121 }
1955 }
2122
1956
2123 for(var i = 0;node = tmp_cache[i];i++){
1957 for(var i = 0;node = tmp_cache[i];i++){
2124 ac.options[i] = node;
1958 ac.options[i] = node;
2125 }
1959 }
2126
1960
2127 function prompts_action_callback(e){
1961 function prompts_action_callback(e){
2128
1962
2129 var chosen = YUD.get(selected_container);
1963 var chosen = YUD.get(selected_container);
2130 var available = YUD.get(available_container);
1964 var available = YUD.get(available_container);
2131
1965
2132 //get checked and unchecked options from field
1966 //get checked and unchecked options from field
2133 function get_checked(from_field){
1967 function get_checked(from_field){
2134 //temp container for storage.
1968 //temp container for storage.
2135 var sel_cache = new Array();
1969 var sel_cache = new Array();
2136 var oth_cache = new Array();
1970 var oth_cache = new Array();
2137
1971
2138 for(var i = 0;node = from_field.options[i];i++){
1972 for(var i = 0;node = from_field.options[i];i++){
2139 if(node.selected){
1973 if(node.selected){
2140 //push selected fields :)
1974 //push selected fields :)
2141 sel_cache.push(node);
1975 sel_cache.push(node);
2142 }
1976 }
2143 else{
1977 else{
2144 oth_cache.push(node)
1978 oth_cache.push(node)
2145 }
1979 }
2146 }
1980 }
2147
1981
2148 return [sel_cache,oth_cache]
1982 return [sel_cache,oth_cache]
2149 }
1983 }
2150
1984
2151 //fill the field with given options
1985 //fill the field with given options
2152 function fill_with(field,options){
1986 function fill_with(field,options){
2153 //clear firtst
1987 //clear firtst
2154 field.options.length=0;
1988 field.options.length=0;
2155 for(var i = 0;node = options[i];i++){
1989 for(var i = 0;node = options[i];i++){
2156 field.options[i]=new Option(node.text, node.value,
1990 field.options[i]=new Option(node.text, node.value,
2157 false, false);
1991 false, false);
2158 }
1992 }
2159
1993
2160 }
1994 }
2161 //adds to current field
1995 //adds to current field
2162 function add_to(field,options){
1996 function add_to(field,options){
2163 for(var i = 0;node = options[i];i++){
1997 for(var i = 0;node = options[i];i++){
2164 field.appendChild(new Option(node.text, node.value,
1998 field.appendChild(new Option(node.text, node.value,
2165 false, false));
1999 false, false));
2166 }
2000 }
2167 }
2001 }
2168
2002
2169 // add action
2003 // add action
2170 if (this.id=='add_element'){
2004 if (this.id=='add_element'){
2171 var c = get_checked(available);
2005 var c = get_checked(available);
2172 add_to(chosen,c[0]);
2006 add_to(chosen,c[0]);
2173 fill_with(available,c[1]);
2007 fill_with(available,c[1]);
2174 }
2008 }
2175 // remove action
2009 // remove action
2176 if (this.id=='remove_element'){
2010 if (this.id=='remove_element'){
2177 var c = get_checked(chosen);
2011 var c = get_checked(chosen);
2178 add_to(available,c[0]);
2012 add_to(available,c[0]);
2179 fill_with(chosen,c[1]);
2013 fill_with(chosen,c[1]);
2180 }
2014 }
2181 // add all elements
2015 // add all elements
2182 if(this.id=='add_all_elements'){
2016 if(this.id=='add_all_elements'){
2183 for(var i=0; node = available.options[i];i++){
2017 for(var i=0; node = available.options[i];i++){
2184 chosen.appendChild(new Option(node.text,
2018 chosen.appendChild(new Option(node.text,
2185 node.value, false, false));
2019 node.value, false, false));
2186 }
2020 }
2187 available.options.length = 0;
2021 available.options.length = 0;
2188 }
2022 }
2189 //remove all elements
2023 //remove all elements
2190 if(this.id=='remove_all_elements'){
2024 if(this.id=='remove_all_elements'){
2191 for(var i=0; node = chosen.options[i];i++){
2025 for(var i=0; node = chosen.options[i];i++){
2192 available.appendChild(new Option(node.text,
2026 available.appendChild(new Option(node.text,
2193 node.value, false, false));
2027 node.value, false, false));
2194 }
2028 }
2195 chosen.options.length = 0;
2029 chosen.options.length = 0;
2196 }
2030 }
2197
2031
2198 }
2032 }
2199
2033
2200 YUE.addListener(['add_element','remove_element',
2034 YUE.addListener(['add_element','remove_element',
2201 'add_all_elements','remove_all_elements'],'click',
2035 'add_all_elements','remove_all_elements'],'click',
2202 prompts_action_callback)
2036 prompts_action_callback)
2203 if (form_id !== undefined) {
2037 if (form_id !== undefined) {
2204 YUE.addListener(form_id,'submit',function(){
2038 YUE.addListener(form_id,'submit',function(){
2205 var chosen = YUD.get(selected_container);
2039 var chosen = YUD.get(selected_container);
2206 for (var i = 0; i < chosen.options.length; i++) {
2040 for (var i = 0; i < chosen.options.length; i++) {
2207 chosen.options[i].selected = 'selected';
2041 chosen.options[i].selected = 'selected';
2208 }
2042 }
2209 });
2043 });
2210 }
2044 }
2211 }
2045 }
2212
2046
2213 // custom paginator
2047 // custom paginator
2214 var YUI_paginator = function(links_per_page, containers){
2048 var YUI_paginator = function(links_per_page, containers){
2215
2049
2216 (function () {
2050 (function () {
2217
2051
2218 var Paginator = YAHOO.widget.Paginator,
2052 var Paginator = YAHOO.widget.Paginator,
2219 l = YAHOO.lang,
2053 l = YAHOO.lang,
2220 setId = YAHOO.util.Dom.generateId;
2054 setId = YAHOO.util.Dom.generateId;
2221
2055
2222 Paginator.ui.MyFirstPageLink = function (p) {
2056 Paginator.ui.MyFirstPageLink = function (p) {
2223 this.paginator = p;
2057 this.paginator = p;
2224
2058
2225 p.subscribe('recordOffsetChange',this.update,this,true);
2059 p.subscribe('recordOffsetChange',this.update,this,true);
2226 p.subscribe('rowsPerPageChange',this.update,this,true);
2060 p.subscribe('rowsPerPageChange',this.update,this,true);
2227 p.subscribe('totalRecordsChange',this.update,this,true);
2061 p.subscribe('totalRecordsChange',this.update,this,true);
2228 p.subscribe('destroy',this.destroy,this,true);
2062 p.subscribe('destroy',this.destroy,this,true);
2229
2063
2230 // TODO: make this work
2064 // TODO: make this work
2231 p.subscribe('firstPageLinkLabelChange',this.update,this,true);
2065 p.subscribe('firstPageLinkLabelChange',this.update,this,true);
2232 p.subscribe('firstPageLinkClassChange',this.update,this,true);
2066 p.subscribe('firstPageLinkClassChange',this.update,this,true);
2233 };
2067 };
2234
2068
2235 Paginator.ui.MyFirstPageLink.init = function (p) {
2069 Paginator.ui.MyFirstPageLink.init = function (p) {
2236 p.setAttributeConfig('firstPageLinkLabel', {
2070 p.setAttributeConfig('firstPageLinkLabel', {
2237 value : 1,
2071 value : 1,
2238 validator : l.isString
2072 validator : l.isString
2239 });
2073 });
2240 p.setAttributeConfig('firstPageLinkClass', {
2074 p.setAttributeConfig('firstPageLinkClass', {
2241 value : 'yui-pg-first',
2075 value : 'yui-pg-first',
2242 validator : l.isString
2076 validator : l.isString
2243 });
2077 });
2244 p.setAttributeConfig('firstPageLinkTitle', {
2078 p.setAttributeConfig('firstPageLinkTitle', {
2245 value : 'First Page',
2079 value : 'First Page',
2246 validator : l.isString
2080 validator : l.isString
2247 });
2081 });
2248 };
2082 };
2249
2083
2250 // Instance members and methods
2084 // Instance members and methods
2251 Paginator.ui.MyFirstPageLink.prototype = {
2085 Paginator.ui.MyFirstPageLink.prototype = {
2252 current : null,
2086 current : null,
2253 leftmost_page: null,
2087 leftmost_page: null,
2254 rightmost_page: null,
2088 rightmost_page: null,
2255 link : null,
2089 link : null,
2256 span : null,
2090 span : null,
2257 dotdot : null,
2091 dotdot : null,
2258 getPos : function(cur_page, max_page, items){
2092 getPos : function(cur_page, max_page, items){
2259 var edge = parseInt(items / 2) + 1;
2093 var edge = parseInt(items / 2) + 1;
2260 if (cur_page <= edge){
2094 if (cur_page <= edge){
2261 var radius = Math.max(parseInt(items / 2), items - cur_page);
2095 var radius = Math.max(parseInt(items / 2), items - cur_page);
2262 }
2096 }
2263 else if ((max_page - cur_page) < edge) {
2097 else if ((max_page - cur_page) < edge) {
2264 var radius = (items - 1) - (max_page - cur_page);
2098 var radius = (items - 1) - (max_page - cur_page);
2265 }
2099 }
2266 else{
2100 else{
2267 var radius = parseInt(items / 2);
2101 var radius = parseInt(items / 2);
2268 }
2102 }
2269
2103
2270 var left = Math.max(1, (cur_page - (radius)))
2104 var left = Math.max(1, (cur_page - (radius)))
2271 var right = Math.min(max_page, cur_page + (radius))
2105 var right = Math.min(max_page, cur_page + (radius))
2272 return [left, cur_page, right]
2106 return [left, cur_page, right]
2273 },
2107 },
2274 render : function (id_base) {
2108 render : function (id_base) {
2275 var p = this.paginator,
2109 var p = this.paginator,
2276 c = p.get('firstPageLinkClass'),
2110 c = p.get('firstPageLinkClass'),
2277 label = p.get('firstPageLinkLabel'),
2111 label = p.get('firstPageLinkLabel'),
2278 title = p.get('firstPageLinkTitle');
2112 title = p.get('firstPageLinkTitle');
2279
2113
2280 this.link = document.createElement('a');
2114 this.link = document.createElement('a');
2281 this.span = document.createElement('span');
2115 this.span = document.createElement('span');
2282 YUD.setStyle(this.span, 'display', 'none');
2116 YUD.setStyle(this.span, 'display', 'none');
2283
2117
2284 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2118 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2285 this.leftmost_page = _pos[0];
2119 this.leftmost_page = _pos[0];
2286 this.rightmost_page = _pos[2];
2120 this.rightmost_page = _pos[2];
2287
2121
2288 setId(this.link, id_base + '-first-link');
2122 setId(this.link, id_base + '-first-link');
2289 this.link.href = '#';
2123 this.link.href = '#';
2290 this.link.className = c;
2124 this.link.className = c;
2291 this.link.innerHTML = label;
2125 this.link.innerHTML = label;
2292 this.link.title = title;
2126 this.link.title = title;
2293 YAHOO.util.Event.on(this.link,'click',this.onClick,this,true);
2127 YAHOO.util.Event.on(this.link,'click',this.onClick,this,true);
2294
2128
2295 setId(this.span, id_base + '-first-span');
2129 setId(this.span, id_base + '-first-span');
2296 this.span.className = c;
2130 this.span.className = c;
2297 this.span.innerHTML = label;
2131 this.span.innerHTML = label;
2298
2132
2299 this.current = p.getCurrentPage() > 1 ? this.link : this.span;
2133 this.current = p.getCurrentPage() > 1 ? this.link : this.span;
2300 return this.current;
2134 return this.current;
2301 },
2135 },
2302 update : function (e) {
2136 update : function (e) {
2303 var p = this.paginator;
2137 var p = this.paginator;
2304 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2138 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2305 this.leftmost_page = _pos[0];
2139 this.leftmost_page = _pos[0];
2306 this.rightmost_page = _pos[2];
2140 this.rightmost_page = _pos[2];
2307
2141
2308 if (e && e.prevValue === e.newValue) {
2142 if (e && e.prevValue === e.newValue) {
2309 return;
2143 return;
2310 }
2144 }
2311
2145
2312 var par = this.current ? this.current.parentNode : null;
2146 var par = this.current ? this.current.parentNode : null;
2313 if (this.leftmost_page > 1) {
2147 if (this.leftmost_page > 1) {
2314 if (par && this.current === this.span) {
2148 if (par && this.current === this.span) {
2315 par.replaceChild(this.link,this.current);
2149 par.replaceChild(this.link,this.current);
2316 this.current = this.link;
2150 this.current = this.link;
2317 }
2151 }
2318 } else {
2152 } else {
2319 if (par && this.current === this.link) {
2153 if (par && this.current === this.link) {
2320 par.replaceChild(this.span,this.current);
2154 par.replaceChild(this.span,this.current);
2321 this.current = this.span;
2155 this.current = this.span;
2322 }
2156 }
2323 }
2157 }
2324 },
2158 },
2325 destroy : function () {
2159 destroy : function () {
2326 YAHOO.util.Event.purgeElement(this.link);
2160 YAHOO.util.Event.purgeElement(this.link);
2327 this.current.parentNode.removeChild(this.current);
2161 this.current.parentNode.removeChild(this.current);
2328 this.link = this.span = null;
2162 this.link = this.span = null;
2329 },
2163 },
2330 onClick : function (e) {
2164 onClick : function (e) {
2331 YAHOO.util.Event.stopEvent(e);
2165 YAHOO.util.Event.stopEvent(e);
2332 this.paginator.setPage(1);
2166 this.paginator.setPage(1);
2333 }
2167 }
2334 };
2168 };
2335
2169
2336 })();
2170 })();
2171
2337 (function () {
2172 (function () {
2338
2173
2339 var Paginator = YAHOO.widget.Paginator,
2174 var Paginator = YAHOO.widget.Paginator,
2340 l = YAHOO.lang,
2175 l = YAHOO.lang,
2341 setId = YAHOO.util.Dom.generateId;
2176 setId = YAHOO.util.Dom.generateId;
2342
2177
2343 Paginator.ui.MyLastPageLink = function (p) {
2178 Paginator.ui.MyLastPageLink = function (p) {
2344 this.paginator = p;
2179 this.paginator = p;
2345
2180
2346 p.subscribe('recordOffsetChange',this.update,this,true);
2181 p.subscribe('recordOffsetChange',this.update,this,true);
2347 p.subscribe('rowsPerPageChange',this.update,this,true);
2182 p.subscribe('rowsPerPageChange',this.update,this,true);
2348 p.subscribe('totalRecordsChange',this.update,this,true);
2183 p.subscribe('totalRecordsChange',this.update,this,true);
2349 p.subscribe('destroy',this.destroy,this,true);
2184 p.subscribe('destroy',this.destroy,this,true);
2350
2185
2351 // TODO: make this work
2186 // TODO: make this work
2352 p.subscribe('lastPageLinkLabelChange',this.update,this,true);
2187 p.subscribe('lastPageLinkLabelChange',this.update,this,true);
2353 p.subscribe('lastPageLinkClassChange', this.update,this,true);
2188 p.subscribe('lastPageLinkClassChange', this.update,this,true);
2354 };
2189 };
2355
2190
2356 Paginator.ui.MyLastPageLink.init = function (p) {
2191 Paginator.ui.MyLastPageLink.init = function (p) {
2357 p.setAttributeConfig('lastPageLinkLabel', {
2192 p.setAttributeConfig('lastPageLinkLabel', {
2358 value : -1,
2193 value : -1,
2359 validator : l.isString
2194 validator : l.isString
2360 });
2195 });
2361 p.setAttributeConfig('lastPageLinkClass', {
2196 p.setAttributeConfig('lastPageLinkClass', {
2362 value : 'yui-pg-last',
2197 value : 'yui-pg-last',
2363 validator : l.isString
2198 validator : l.isString
2364 });
2199 });
2365 p.setAttributeConfig('lastPageLinkTitle', {
2200 p.setAttributeConfig('lastPageLinkTitle', {
2366 value : 'Last Page',
2201 value : 'Last Page',
2367 validator : l.isString
2202 validator : l.isString
2368 });
2203 });
2369
2204
2370 };
2205 };
2371
2206
2372 Paginator.ui.MyLastPageLink.prototype = {
2207 Paginator.ui.MyLastPageLink.prototype = {
2373
2208
2374 current : null,
2209 current : null,
2375 leftmost_page: null,
2210 leftmost_page: null,
2376 rightmost_page: null,
2211 rightmost_page: null,
2377 link : null,
2212 link : null,
2378 span : null,
2213 span : null,
2379 dotdot : null,
2214 dotdot : null,
2380 na : null,
2215 na : null,
2381 getPos : function(cur_page, max_page, items){
2216 getPos : function(cur_page, max_page, items){
2382 var edge = parseInt(items / 2) + 1;
2217 var edge = parseInt(items / 2) + 1;
2383 if (cur_page <= edge){
2218 if (cur_page <= edge){
2384 var radius = Math.max(parseInt(items / 2), items - cur_page);
2219 var radius = Math.max(parseInt(items / 2), items - cur_page);
2385 }
2220 }
2386 else if ((max_page - cur_page) < edge) {
2221 else if ((max_page - cur_page) < edge) {
2387 var radius = (items - 1) - (max_page - cur_page);
2222 var radius = (items - 1) - (max_page - cur_page);
2388 }
2223 }
2389 else{
2224 else{
2390 var radius = parseInt(items / 2);
2225 var radius = parseInt(items / 2);
2391 }
2226 }
2392
2227
2393 var left = Math.max(1, (cur_page - (radius)))
2228 var left = Math.max(1, (cur_page - (radius)))
2394 var right = Math.min(max_page, cur_page + (radius))
2229 var right = Math.min(max_page, cur_page + (radius))
2395 return [left, cur_page, right]
2230 return [left, cur_page, right]
2396 },
2231 },
2397 render : function (id_base) {
2232 render : function (id_base) {
2398 var p = this.paginator,
2233 var p = this.paginator,
2399 c = p.get('lastPageLinkClass'),
2234 c = p.get('lastPageLinkClass'),
2400 label = p.get('lastPageLinkLabel'),
2235 label = p.get('lastPageLinkLabel'),
2401 last = p.getTotalPages(),
2236 last = p.getTotalPages(),
2402 title = p.get('lastPageLinkTitle');
2237 title = p.get('lastPageLinkTitle');
2403
2238
2404 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2239 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2405 this.leftmost_page = _pos[0];
2240 this.leftmost_page = _pos[0];
2406 this.rightmost_page = _pos[2];
2241 this.rightmost_page = _pos[2];
2407
2242
2408 this.link = document.createElement('a');
2243 this.link = document.createElement('a');
2409 this.span = document.createElement('span');
2244 this.span = document.createElement('span');
2410 YUD.setStyle(this.span, 'display', 'none');
2245 YUD.setStyle(this.span, 'display', 'none');
2411
2246
2412 this.na = this.span.cloneNode(false);
2247 this.na = this.span.cloneNode(false);
2413
2248
2414 setId(this.link, id_base + '-last-link');
2249 setId(this.link, id_base + '-last-link');
2415 this.link.href = '#';
2250 this.link.href = '#';
2416 this.link.className = c;
2251 this.link.className = c;
2417 this.link.innerHTML = label;
2252 this.link.innerHTML = label;
2418 this.link.title = title;
2253 this.link.title = title;
2419 YAHOO.util.Event.on(this.link,'click',this.onClick,this,true);
2254 YAHOO.util.Event.on(this.link,'click',this.onClick,this,true);
2420
2255
2421 setId(this.span, id_base + '-last-span');
2256 setId(this.span, id_base + '-last-span');
2422 this.span.className = c;
2257 this.span.className = c;
2423 this.span.innerHTML = label;
2258 this.span.innerHTML = label;
2424
2259
2425 setId(this.na, id_base + '-last-na');
2260 setId(this.na, id_base + '-last-na');
2426
2261
2427 if (this.rightmost_page < p.getTotalPages()){
2262 if (this.rightmost_page < p.getTotalPages()){
2428 this.current = this.link;
2263 this.current = this.link;
2429 }
2264 }
2430 else{
2265 else{
2431 this.current = this.span;
2266 this.current = this.span;
2432 }
2267 }
2433
2268
2434 this.current.innerHTML = p.getTotalPages();
2269 this.current.innerHTML = p.getTotalPages();
2435 return this.current;
2270 return this.current;
2436 },
2271 },
2437
2272
2438 update : function (e) {
2273 update : function (e) {
2439 var p = this.paginator;
2274 var p = this.paginator;
2440
2275
2441 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2276 var _pos = this.getPos(p.getCurrentPage(), p.getTotalPages(), 5);
2442 this.leftmost_page = _pos[0];
2277 this.leftmost_page = _pos[0];
2443 this.rightmost_page = _pos[2];
2278 this.rightmost_page = _pos[2];
2444
2279
2445 if (e && e.prevValue === e.newValue) {
2280 if (e && e.prevValue === e.newValue) {
2446 return;
2281 return;
2447 }
2282 }
2448
2283
2449 var par = this.current ? this.current.parentNode : null,
2284 var par = this.current ? this.current.parentNode : null,
2450 after = this.link;
2285 after = this.link;
2451 if (par) {
2286 if (par) {
2452
2287
2453 // only show the last page if the rightmost one is
2288 // only show the last page if the rightmost one is
2454 // lower, so we don't have doubled entries at the end
2289 // lower, so we don't have doubled entries at the end
2455 if (!(this.rightmost_page < p.getTotalPages())){
2290 if (!(this.rightmost_page < p.getTotalPages())){
2456 after = this.span
2291 after = this.span
2457 }
2292 }
2458
2293
2459 if (this.current !== after) {
2294 if (this.current !== after) {
2460 par.replaceChild(after,this.current);
2295 par.replaceChild(after,this.current);
2461 this.current = after;
2296 this.current = after;
2462 }
2297 }
2463 }
2298 }
2464 this.current.innerHTML = this.paginator.getTotalPages();
2299 this.current.innerHTML = this.paginator.getTotalPages();
2465
2300
2466 },
2301 },
2467 destroy : function () {
2302 destroy : function () {
2468 YAHOO.util.Event.purgeElement(this.link);
2303 YAHOO.util.Event.purgeElement(this.link);
2469 this.current.parentNode.removeChild(this.current);
2304 this.current.parentNode.removeChild(this.current);
2470 this.link = this.span = null;
2305 this.link = this.span = null;
2471 },
2306 },
2472 onClick : function (e) {
2307 onClick : function (e) {
2473 YAHOO.util.Event.stopEvent(e);
2308 YAHOO.util.Event.stopEvent(e);
2474 this.paginator.setPage(this.paginator.getTotalPages());
2309 this.paginator.setPage(this.paginator.getTotalPages());
2475 }
2310 }
2476 };
2311 };
2477
2312
2478 })();
2313 })();
2479
2314
2480 var pagi = new YAHOO.widget.Paginator({
2315 var pagi = new YAHOO.widget.Paginator({
2481 rowsPerPage: links_per_page,
2316 rowsPerPage: links_per_page,
2482 alwaysVisible: false,
2317 alwaysVisible: false,
2483 template : "{PreviousPageLink} {MyFirstPageLink} {PageLinks} {MyLastPageLink} {NextPageLink}",
2318 template : "{PreviousPageLink} {MyFirstPageLink} {PageLinks} {MyLastPageLink} {NextPageLink}",
2484 pageLinks: 5,
2319 pageLinks: 5,
2485 containerClass: 'pagination-wh',
2320 containerClass: 'pagination-wh',
2486 currentPageClass: 'pager_curpage',
2321 currentPageClass: 'pager_curpage',
2487 pageLinkClass: 'pager_link',
2322 pageLinkClass: 'pager_link',
2488 nextPageLinkLabel: '&gt;',
2323 nextPageLinkLabel: '&gt;',
2489 previousPageLinkLabel: '&lt;',
2324 previousPageLinkLabel: '&lt;',
2490 containers:containers
2325 containers:containers
2491 })
2326 })
2492
2327
2493 return pagi
2328 return pagi
2494 }
2329 }
2495
2330
2496
2331
2497
2498 // global hooks after DOM is loaded
2332 // global hooks after DOM is loaded
2499
2333
2500 YUE.onDOMReady(function(){
2334 YUE.onDOMReady(function(){
2501 YUE.on(YUQ('.diff-collapse-button'), 'click', function(e){
2335 YUE.on(YUQ('.diff-collapse-button'), 'click', function(e){
2502 var button = e.currentTarget;
2336 var button = e.currentTarget;
2503 var t = YUD.get(button).getAttribute('target');
2337 var t = YUD.get(button).getAttribute('target');
2504 console.log(t);
2338 console.log(t);
2505 if(YUD.hasClass(t, 'hidden')){
2339 if(YUD.hasClass(t, 'hidden')){
2506 YUD.removeClass(t, 'hidden');
2340 YUD.removeClass(t, 'hidden');
2507 YUD.get(button).innerHTML = "&uarr; {0} &uarr;".format(_TM['Collapse diff']);
2341 YUD.get(button).innerHTML = "&uarr; {0} &uarr;".format(_TM['Collapse diff']);
2508 }
2342 }
2509 else if(!YUD.hasClass(t, 'hidden')){
2343 else if(!YUD.hasClass(t, 'hidden')){
2510 YUD.addClass(t, 'hidden');
2344 YUD.addClass(t, 'hidden');
2511 YUD.get(button).innerHTML = "&darr; {0} &darr;".format(_TM['Expand diff']);
2345 YUD.get(button).innerHTML = "&darr; {0} &darr;".format(_TM['Expand diff']);
2512 }
2346 }
2513 });
2347 });
2514
2515
2516
2517 });
2348 });
General Comments 0
You need to be logged in to leave comments. Login now