1 define('contextmenu', ['ClipBoard','jquery', 'jsPanel','ClipBoard'], function(ClipBoard, $) {
  2 		/**
  3 		 * A Class to handle the context menu of the workbook, The context menu is devided into three, Like Row Context menu, Column Context menu, Data Table Context menu.
  4 		 * @name contextmenu
  5 		 * @class contextmenu
  6 		 * @example require('contextmenu')
  7 		 * @exports contextmenu
  8 		 * @version 1.0
  9 		 * @module contextmenu
 10 		 * @augments jquery
 11 		 * @augments jsPanel
 12 		 **/
 13 	return {
 14 		/**
 15 		 * Object EVENT_TARGET the target in which the context menu event happened will be recorded here. 
 16 		 * @name EVENT_TARGET
 17 		 * @exports EVENT_TARGET 
 18 		 * @version 1.0
 19 		 * @module contextmenu
 20 		 * @memberOf contextmenu
 21 		 * @field
 22 		 **/
 23 		EVENT_TARGET : '',
 24 		/**
 25 		 * @name init
 26 		 * @memberOf contextmenu
 27 		 * @method 
 28 		 * @description Setup all the context menu associated with the Row, COlumn and data table including the Sheet Tabs.
 29 		 * @function
 30 		 * 
 31 		 */
 32 		init : function() {
 33 			
 34 			$('.colsHeaderDiv').contextmenu({
 35 				before : function(e, context) {
 36 					// execute code before context menu if shown
 37 					var CONTEXT_MENU = require('contextmenu');
 38 					var MENU_ITEMS = CONTEXT_MENU.MENU_ITEMS; 
 39 					var meuItems = [];
 40 					meuItems.push(MENU_ITEMS.INSERT_1_LEFT);
 41 					meuItems.push(MENU_ITEMS.INSERT_1_RIGHT);
 42 					meuItems.push(MENU_ITEMS.DELETE_COLUMN);
 43 					meuItems.push(MENU_ITEMS.CLEAR_COLUMN);
 44 					require('contextmenu').setupMenuItem(meuItems);//["Add column after", "Add col before", "Clear Column"]);
 45 				},
 46 				onItem : function(context, e) {
 47 					// execute on menu item selection
 48 					//TODO Add row functionality to integrated.
 49 					require('contextmenu').menuEvent($(e.target).html());
 50 				}
 51 			});
 52 			$('.rowTableDiv').contextmenu({
 53 				before : function(e, context) {
 54 					// execute code before context menu if shown
 55 					var CONTEXT_MENU = require('contextmenu');
 56 					var MENU_ITEMS = CONTEXT_MENU.MENU_ITEMS; 
 57 					var meuItems = [];
 58 					meuItems.push(MENU_ITEMS.INSERT_1_BEFORE);
 59 					meuItems.push(MENU_ITEMS.INSERT_1_AFTER);
 60 					meuItems.push(MENU_ITEMS.DELETE_ROW);
 61 					meuItems.push(MENU_ITEMS.CLEAR_ROW);
 62 					require('contextmenu').setupMenuItem(meuItems);//["Add row above", "Add row below", "Clear row"]);
 63 				},
 64 				onItem : function(context, e) {
 65 					//TODO Add column functionality to integrated.
 66 					require('contextmenu').menuEvent($(e.target).html());
 67 				}
 68 			});
 69 			$('.dataTableDiv').contextmenu({
 70 				before : function(e, context) {
 71 					// execute code before context menu if shown
 72 					var col = $(e.target).index();
 73 					var row = $(e.target).parent().index();
 74 					var HANDLER = require('HANDLER');
 75 					var MouseListener = require('MouseListener');
 76 					var GridView = require('GridView');
 77 					var selection = MouseListener.getOrderedSelectionPos(HANDLER.SELECTION_HANDLER);
 78 					var CONTEXT_MENU = require('contextmenu');
 79 					var MENU_ITEMS = CONTEXT_MENU.MENU_ITEMS; 
 80 					var meuItems = [];
 81 
 82 					if (((selection.START_ROW == 0 || selection.START_ROW ) && col <= selection.CURR_COL && col >= selection.START_COL && row <= selection.CURR_ROW && row >= selection.START_ROW) && !MouseListener.isSingleCellSelection(selection)) {
 83 						meuItems.push(MENU_ITEMS.CUT);
 84 						meuItems.push(MENU_ITEMS.COPY);
 85 						//meuItems.push(MENU_ITEMS.PASTE);
 86 						meuItems.push(MENU_ITEMS.MENU_DEVIDER);
 87 						meuItems.push(MENU_ITEMS.CREATE_GROUP);
 88 					} else {
 89 						var WorkBook = require('WorkBook');
 90 						var groups = GridView.getGroupsOnCell(WorkBook.ACTIVE_SHEET_ID, row + 1, col + 1);
 91 						if (HANDLER.LAST_SELECTION)
 92 							GridView.highlightSelectionArea(HANDLER.LAST_SELECTION, require('DomObjects').defaultBorderCol);
 93 						// Removing Selection Highlight
 94 						//require('GridView').highlightCell(target);	// Highlighting Cell
 95 						selection.CURR_ROW = row;
 96 						selection.CURR_COL = col;
 97 						selection.START_ROW = row;
 98 						selection.START_COL = col;
 99 						GridView.highlightCell(e.target, true);
100 						GridView.CELL_DRAG.positionSelectionCornerDiv(e.target);
101 						MouseListener.updateSelectionOnGroupWithFormulaCell(selection, WorkBook.ACTIVE_SHEET_ID, row + 1, col + 1);
102 						GridView.highlightSelectionArea(selection, require('DomObjects').selectionAreaBorderColor);
103 						HANDLER.LAST_SELECTION = selection;
104 						MouseListener.setSelectionHandler(selection.START_ROW, selection.START_COL, selection.CURR_ROW, selection.CURR_COL);
105 						// Single Selection is SET.
106 						CONTEXT_MENU.EVENT_TARGET = [];
107 
108 						if (groups.length > 0) {
109 							var formula = false;
110 							for (var i = 0; i < groups.length; i++) {
111 								var groupObj = groups[i];
112 								if (groupObj.formula) {
113 									CONTEXT_MENU.EVENT_TARGET = [];
114 									// Keeping only one
115 									formula = true;
116 								}
117 								CONTEXT_MENU.EVENT_TARGET.push(groupObj);
118 								GridView.highlighGroupByGroupObj(groupObj, groupObj.color);
119 							}
120 							if (!formula)
121 								meuItems.push(MENU_ITEMS.CUT);
122 							meuItems.push(MENU_ITEMS.COPY);
123 							/*if (!formula)
124 								meuItems.push(MENU_ITEMS.PASTE);*/
125 							if (groups.length == 1) {
126 								meuItems.push(MENU_ITEMS.MENU_DEVIDER);
127 								meuItems.push(MENU_ITEMS.COPY_GROUP);
128 								meuItems.push(MENU_ITEMS.EDIT_GROUP);
129 								meuItems.push(MENU_ITEMS.DELETE_GROUP);
130 								if (!formula)
131 									meuItems.push(MENU_ITEMS.INSERT_GROUP_FORMULA);
132 							}
133 							if (formula) {
134 								meuItems.push(MENU_ITEMS.MENU_DEVIDER);
135 								meuItems.push(MENU_ITEMS.EXPLAIN_GROUP_RESULT);
136 								meuItems.push(MENU_ITEMS.MODIFY_GROUP_FORMULA);
137 								meuItems.push(MENU_ITEMS.REMOVE_GROUP_FORMULA);
138 								meuItems.push(MENU_ITEMS.MENU_DEVIDER);
139 								//meuItems.push(MENU_ITEMS.VIEW_DEPENDENCY_GRAPH));
140 								meuItems.push(MENU_ITEMS.VIEW_EVALUATION_GRAPH);
141 							}
142 						} else {
143 							if (HANDLER.LAST_SELECTION)
144 								GridView.highlightSelectionArea(HANDLER.LAST_SELECTION, require('DomObjects').defaultBorderCol);
145 							if ($($(e.target).parent()).attr('class') != "bottom_block footer") {// Not for Footer
146 								meuItems.push(MENU_ITEMS.CUT);
147 								meuItems.push(MENU_ITEMS.COPY);
148 								//meuItems.push(MENU_ITEMS.PASTE);
149 								//meuItems.push(MENU_ITEMS.MENU_DEVIDER));
150 							} else {
151 								meuItems.push(MENU_ITEMS.ADD_SHEET);
152 								meuItems.push(MENU_ITEMS.DELETE_SHEET);
153 							}
154 						}
155 					}
156 
157 					require('contextmenu').setupMenuItem(meuItems);
158 					console.log('Table Context');
159 				},
160 				onItem : function(context, e) {
161 					// execute on menu item selection
162 					console.log($(e.target).html());
163 					require('contextmenu').menuEvent($(e.target).html());
164 				}
165 			});
166 
167 			$('.SHEET_TAB').each(function() {
168 				require('contextmenu').initTabContextMenu(this);
169 			});
170 		},
171 		/**
172 		 * @name initTabContextMenu
173 		 * @memberOf contextmenu
174 		 * @method 
175 		 * @description Setup context menu for each of the TAB in the workbook.
176 		 * @param {DIV} tab
177 		 * @function
178 		 */
179 		initTabContextMenu : function(tab) {
180 			$(tab).contextmenu({
181 				before : function(e, context) {
182 					// execute code before context menu if shown
183 					var CONTEXT_MENU = require('contextmenu');
184 					var MENU_ITEMS = CONTEXT_MENU.MENU_ITEMS; 
185 					var meuItems = [];
186 					meuItems.push(MENU_ITEMS.ADD_SHEET);
187 					meuItems.push(MENU_ITEMS.RENAME_SHEET);
188 					meuItems.push(MENU_ITEMS.DELETE_SHEET);
189 					require('contextmenu').setupMenuItem(meuItems);
190 
191 				},
192 				onItem : function(context, e) {
193 					// execute on menu item selection
194 					var sheetId = $(context).data('id');
195 					sheetName = (context).find('a').html();
196 					var CONTEXT_MENU = require('contextmenu');
197 					var MENU_ITEMS = CONTEXT_MENU.MENU_ITEMS; 
198 					if (MENU_ITEMS.RENAME_SHEET == $(e.target).html()) {
199 
200 						require('SheetController').renameSheet(sheetId, sheetName);
201 					} else if (MENU_ITEMS.DELETE_SHEET == $(e.target).html()) {
202 						require('SheetController').deleteSheet(sheetId, sheetName);
203 					} else if (MENU_ITEMS.ADD_SHEET == $(e.target).html()) {
204 						require('SheetController').addSheet();
205 					}
206 				}
207 			});
208 		},
209 		/**
210 		 * @name setupMenuItem
211 		 * @memberOf contextmenu
212 		 * @method 
213 		 * @description Method removes all the existing menu items and setup with the items provided here items[] 
214 		 * @param {Object[]} items
215 		 * @function
216 		 */
217 		setupMenuItem : function(items) {
218 			$('.CONTEXT_MENU li').remove();
219 			for ( i = 0; i < items.length; i++) {
220 				var item = items[i];
221 				if (item == 'divider')
222 					$('<li class="divider"></li>').appendTo($('.CONTEXT_MENU'));
223 				else
224 					$('<li><a tabindex="-1">' + item + '</a></li>').appendTo($('.CONTEXT_MENU'));
225 
226 			}
227 		},
228 
229 		/*closeMenu:function(){
230 		 var container = $("#custom-menu");
231 		 //	if (container.has(e.target).length == 0) {
232 		 container.hide();
233 		 //}
234 		 },
235 		 init:function(){
236 		 $(document).bind("contextmenu", function(e) {
237 		 e.preventDefault();
238 		 $('#custom-menu ol li').remove();
239 		 CONTEXT_MENU.postRightClickAction(e.target);
240 		 var top = e.pageY- $(Nexcel.DOM_OBJ.dataTableDiv).offset().top;
241 		 if((e.pageY+$("#custom-menu").height()) > $('div.dataTableDiv').height())
242 		 top = top-$("#custom-menu").height();
243 		 //top = top - $(Nexcel.DOM_OBJ.dataTableDiv).scrollTop();
244 		 var left = 	e.pageX + 45 -  $(Nexcel.DOM_OBJ.dataTableDiv).offset().left;
245 		 $("#custom-menu").css({
246 		 top : (top+84) +"px",// File Menu Div 30 + Control but menu Div 30 + Column Header Div Height + Column Name header Div Height
247 		 left :left+"px" //45=> $('div.rowNumTableDiv').width()
248 		 }).show();
249 		 });
250 		 $(document).mouseup(function(e) {
251 		 if(e.which == 3)
252 		 return;
253 		 CONTEXT_MENU.closeMenu();
254 		 });
255 		 },*/
256 		
257 		/**
258 		 * Object MENU_ITEM The supported all teh menu items in the workbook. 
259 		 * @name MENU_ITEM
260 		 * @exports MENU_ITEM 
261 		 * @version 1.0
262 		 * @module contextmenu
263 		 * @memberOf contextmenu
264 		 * @field
265 		 **/
266 		MENU_ITEMS : {
267 			MENU_DEVIDER : 'divider',
268 			CREATE_GROUP : 'Create group',
269 			EDIT_GROUP : 'Edit group',
270 			DELETE_GROUP : 'Delete group',
271 			INSERT_GROUP_FORMULA : 'Insert group formula',
272 
273 			EXPLAIN_GROUP_RESULT : 'Explain',
274 			MODIFY_GROUP_FORMULA : 'Modify group formula',
275 			REMOVE_GROUP_FORMULA : 'Remove group formula',
276 			VIEW_DEPENDENCY_GRAPH : 'View dependency graph',
277 			VIEW_EVALUATION_GRAPH : 'View evaluation graph',
278 
279 			ADD_SHEET : 'Add sheet',
280 			RENAME_SHEET : 'Rename sheet',
281 			DELETE_SHEET : 'Delete sheet',
282 
283 			CUT : 'Cut',
284 			COPY : 'Copy',
285 			COPY_GROUP : 'Copy group values',
286 			PASTE : 'Paste',
287 
288 			// ROW Menu
289 			INSERT_1_BEFORE : 'Insert 1 above',
290 			INSERT_1_AFTER : 'Insert 1 below',
291 			DELETE_ROW : 'Delete row',
292 			CLEAR_ROW : 'Clear row',
293 
294 			// ROW Menu
295 			INSERT_1_LEFT : 'Insert 1 left',
296 			INSERT_1_RIGHT : 'Insert 1 right',
297 			DELETE_COLUMN : 'Delete column',
298 			CLEAR_COLUMN : 'Clear column',
299 		},
300 		/**
301 		 * @name menuEvent
302 		 * @memberOf contextmenu
303 		 * @method 
304 		 * @description This method is an Action Listener, Once the menu event happens the method will be executes with the action name.
305 		 * @param {String} action
306 		 * @function
307 		 */
308 		menuEvent:function(action){
309 			var MENU_ITEMS = require('contextmenu').MENU_ITEMS; 
310 			if(action ==MENU_ITEMS.CREATE_GROUP)
311 				this.ACTION.createGroup();
312 			else if(action == MENU_ITEMS.EXPLAIN_GROUP_RESULT)
313 				this.ACTION.explainGroupValueCalculation();
314 			else if(action == MENU_ITEMS.MODIFY_GROUP_FORMULA)
315 				this.ACTION.editGroupFormula();
316 			else if(action == MENU_ITEMS.REMOVE_GROUP_FORMULA)
317 				this.ACTION.removeGroupFormula();
318 			else if(action == MENU_ITEMS.INSERT_GROUP_FORMULA)
319 				this.ACTION.applyGroupFormula();
320 			else if(action == MENU_ITEMS.DELETE_GROUP)
321 				this.ACTION.deleteGroup();
322 			else if(action == MENU_ITEMS.EDIT_GROUP)
323 				this.ACTION.editGroup();
324 				
325 
326 			//ROW/COLUMN Associated Actons
327 			else if(action == MENU_ITEMS.CLEAR_ROW)
328 				require('GridView').clearRow();
329 			else if(action == MENU_ITEMS.CLEAR_COLUMN)
330 				require('GridView').clearColumn();
331 			else if(action == MENU_ITEMS.INSERT_1_BEFORE)
332 				require('GridView').ADD_REM_ROW_COL.addRowAbove();
333 			else if(action == MENU_ITEMS.INSERT_1_AFTER)
334 				require('GridView').ADD_REM_ROW_COL.addRowBelow();
335 			else if(action == MENU_ITEMS.INSERT_1_RIGHT)
336 				require('GridView').ADD_REM_ROW_COL.addColumnRight();
337 			else if(action == MENU_ITEMS.INSERT_1_LEFT)
338 				require('GridView').ADD_REM_ROW_COL.addColumnLeft();
339 				
340 			// CELL Associated Actions
341 			else if(action == MENU_ITEMS.CUT)
342 				require('ClipBoard').cut();
343 			else if(action == MENU_ITEMS.COPY)
344 				require('ClipBoard').copy();
345 			else if(action == MENU_ITEMS.COPY_GROUP)
346 				require('ClipBoard').copyGroup();
347 			else if(action == MENU_ITEMS.PASTE)
348 				require('ClipBoard').paste();
349 				
350 			// Evaluation 
351 			else if(action == MENU_ITEMS.VIEW_EVALUATION_GRAPH){
352 				this.ACTION.viewEvaluationGraph();
353 			}
354 				
355 		},
356 		/**
357 		 * ContextMenu based All the actions will be defined under this class.
358 		 * @name ACTION
359 		 * @class ACTION
360 		 * @example require('contextmenu').ACTION
361 		 * @exports ACTION
362 		 * @version 1.0
363 		 * @module contextmenu
364 		 * @memberOf contextmenu
365 		 **/
366 		ACTION:{
367 			/**
368 			 * @name createGroup
369 			 * @memberOf contextmenu.ACTION
370 			 * @method 
371 			 * @description This method calls openCreateGroupModal method to openup the Modal Panel to create a group.
372 			 * @function
373 			 */
374 			createGroup:function(){
375 				//$('#newGroupDiv').remove();
376 				var RENAME_GROUP = false;
377 				this.openCreateGroupModal(RENAME_GROUP);
378 			},
379 			/**
380 			 * @name removeGroupFormula
381 			 * @memberOf contextmenu.ACTION
382 			 * @method 
383 			 * @description It removes teh group formula and will update the server
384 			 * @function
385 			 */
386 			removeGroupFormula:function(){
387 				var groupObj = require('contextmenu').EVENT_TARGET[0];
388 				require(['EditorController'],function(editorController){
389 					groupObj = require('NexcelGroupList').getGroupObjById(groupObj.id);
390 					groupObj.formula=null;
391 					require('NexcelUIDataService').updateGroupFormula(groupObj.id, '');
392 				});
393 			},
394 			/**
395 			 * @name editGroupFormula
396 			 * @memberOf contextmenu.ACTION
397 			 * @method 
398 			 * @description It calls EditorController to open up Expression editor to edit the formula for the group where the user applied meu event.
399 			 * @function
400 			 */
401 			editGroupFormula:function(){
402 				//$('#newGroupDiv').remove();
403 				var groupObj = require('contextmenu').EVENT_TARGET[0];
404 				require(['EditorController'],function(editorController){
405 					editorController.openEditor(groupObj.id, groupObj);	
406 				});
407 			},
408 			/**
409 			 * @name applyGroupFormula
410 			 * @memberOf contextmenu.ACTION
411 			 * @method 
412 			 * @description method to apply group formula for a group without groupformula, it calls Editor Controller to open up and the groupObject will be passed.
413 			 * @function
414 			 */
415 			applyGroupFormula:function(){
416 				//$('#newGroupDiv').remove();
417 				var groupObj = require('contextmenu').EVENT_TARGET[0];
418 				var group = require('NexcelUI').isPartOfAnyGroupWithGroupFormula(groupObj);
419 				if(group){
420 					modal({
421 						type  : 'error',
422 						title : 'Warning! Cannot insert formula',
423 						text  : "The selected group is a part of group "+group.name+", which have a formula."
424 					});
425 				}else
426 					require(['EditorController'],function(editorController){
427 						editorController.openEditor(groupObj.id, groupObj);	
428 					});
429 			},
430 			/**
431 			 * @name explainGroupValueCalculation
432 			 * @memberOf contextmenu.ACTION
433 			 * @method 
434 			 * @description method to present Explanation Graph UI by calling the GraphController
435 			 * @function
436 			 */
437 			explainGroupValueCalculation:function(){
438 				var cellObj = require('GridView').getHighlightedCellObj();		
439 				var groupObj = require('contextmenu').EVENT_TARGET[0];
440 				var rowContent = [];
441 				for(var i=0; i< groupObj.colSize; i++){
442 					var cellObj = require('NexcelCellList').isExist(groupObj.sheetId, cellObj.getRow(), (parseInt(groupObj.colStart)+i));
443 					if(cellObj)
444 						rowContent[i] = cellObj.getValue();
445 					else
446 						rowContent[i] = "";
447 				}		
448 				console.log('Explain Group Value Calculation. :'+rowContent.join('  -  '));
449 				/*require(['ExplanationUIController'],function(explanationUIController){
450 					//explanationUIController.explainForValues(groupObj, rowContent);
451 					
452 				});*/
453 				require(['GraphController'],function(graphController){
454 					var inputString=groupObj.name+'("'+rowContent.join('","')+'")';
455 					graphController.showExplanationGraph(inputString);	
456 				});
457 			},
458 			/**
459 			 * @name openCreateGroupModal
460 			 * @memberOf contextmenu.ACTION
461 			 * @method 
462 			 * @description It setups the Create Group MDI view contents dynamically.
463 			 * @param {boolean} renameGroup whether it is renaming the group or not.
464 			 * @param oldname if it is renaming the old name should be passed, to present in the view.
465 			 * @function
466 			 */
467 			openCreateGroupModal:function(renameGroup, oldName){
468 				var WorkBook = require('WorkBook');
469 				var arr = [				    
470 				    {
471 				        item: '<button type="button">Cancel</button>',
472 				        event: 'click',
473 				        callback: function(){ 
474 				        		WorkBook.MDI.addWorkBookMDI.close();
475 				        		WorkBook.MDI.addWorkBookMDI = null; 
476 				        	}
477 				    },
478 				    {
479 				        item: '<button type="button">OK</button>',
480 				        event: 'click',
481 				        callback: function(){ 
482 				        	var CONTENT = WorkBook.MDI.addWorkBookMDI.content[0];
483 				        	var newName = $($(CONTENT).find('#groupName')).val();
484 				        	var GridView = require('GridView');
485 							if ( !newName || newName.length == 0) {
486 								$($(CONTENT).find('#messageDiv').find('#errorMessage')).html('Invalid name, the length should be minimum 3 character');
487 								$($(CONTENT).find('#messageDiv')).show();
488 								return false;
489 							}
490 							var showGroupTitle = $($(CONTENT).find("#showGroupTitleCB")[0]).is(':checked');
491 							var showColumnName = $($(CONTENT).find('#columnNameCB')[0]).is(':checked');
492 							var extendToLastRow =$($(CONTENT).find('#extendToLastRowCB')[0]).is(':checked');
493 							function getHeader(){
494 								var inputs = $(CONTENT).find('.column-names-list').find('input');
495 								var headers = [];
496 								for(var i =0;i<inputs.length ;i++){
497 									var val =$(inputs[i]).val();
498 									if(val.length == 0){
499 										showError('Please provide the column names');
500 										return false;
501 									}
502 									headers.push({'col':i,'name':val});
503 								}
504 								return headers;
505 							}
506 							if(!renameGroup){
507 								
508 								function showError(msg){
509 									$('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span id="errorMessage"><strong>Error!</strong> '+msg+'</span>		</div>').appendTo($(CONTENT).find('#messageDiv'));
510 									$(CONTENT).find('#messageDiv').show();
511 								}
512 								function showSuccess(msg){
513 									$('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span id="errorMessage"><strong>Success ! </strong> '+msg+'</span>		</div>').appendTo($(CONTENT).find('#messageDiv'));
514 									$(CONTENT).find('#messageDiv').show();
515 								}
516 								var NexcelGroupList = require('NexcelGroupList');
517 								if(NexcelGroupList.isExist(newName)){
518 									showError('Group name already exists.. Please use another name !');
519 									return;
520 								}
521 								
522 								var SELECTION_AREA;
523 								if($("input[name=inputType]:checked").val() == "SELECTION"){
524 									if(!getHeader()) return false;
525 									SELECTION_AREA = require('MouseListener').getOrderedSelectionPos(HANDLER.SELECTION_HANDLER);
526 								
527 								}else if($("input[name=inputType]:checked").val() == "RANGE"){
528 									var ranges = $(CONTENT).find('#rangeValueTxt').val();
529 									ranges = ranges.split(':');
530 									if(ranges.length!=2){
531 										showError('Invalid range value..');
532 										return;
533 									} 
534 									var startLoc = require('GridView').parseLocation(ranges[0]);
535 									SELECTION_AREA=new Object();
536 									SELECTION_AREA.START_COL = startLoc.col;
537 									SELECTION_AREA.START_ROW = startLoc.row;
538 									var endLoc = GridView.parseLocation(ranges[1]);
539 									SELECTION_AREA.CURR_COL = endLoc.col;
540 									SELECTION_AREA.CURR_ROW = endLoc.row;
541 								}
542 								
543 										// Adding new header Objects to the Selection. is done by Apply Header method
544 								/*if(showColumnName || showGroupTitle){
545 									var columns= SELECTION_AREA.CURR_COL - SELECTION_AREA.START_COL +1;
546 									if(SELECTION_AREA.START_ROW<1){
547 										showError('Not enough space for header');
548 										return;
549 									}
550 									/*for(var i=0; i< columns; i++){
551 										var groupsWithFormula = GridView.isCellAssociatedWithGroupWithFormula(SELECTION_AREA.START_ROW, SELECTION_AREA.START_COL+i+1, WorkBook.ACTIVE_SHEET_ID);
552 										if(groupsWithFormula){
553 											showError('Cannot create group, the header is a part of a group with formula');
554 											return;
555 										}
556 									}	
557 									//SELECTION_AREA.START_ROW = SELECTION_AREA.START_ROW-1;
558 																
559 								}
560 								if(showColumnName && showGroupTitle){
561 									var columns= SELECTION_AREA.CURR_COL - SELECTION_AREA.START_COL +1;
562 									if(SELECTION_AREA.START_ROW<1){
563 										showError('Not enough space for header & title');
564 										return;
565 									}
566 									for(var i=0; i< columns; i++){
567 										var groupsWithFormula = GridView.isCellAssociatedWithGroupWithFormula(SELECTION_AREA.START_ROW, SELECTION_AREA.START_COL+i+1, WorkBook.ACTIVE_SHEET_ID);
568 										if(groupsWithFormula){
569 											showError('Cannot create group, the header is apart of group with formula');
570 											return;
571 										}
572 									}	
573 									SELECTION_AREA.START_ROW = SELECTION_AREA.START_ROW-1;						
574 								}	*/
575 								//NOTE : following code to change 1,1 is considered as first cell A1. 
576 								if(extendToLastRow && $("input[name=inputType]:checked").val() == "SELECTION")
577 									SELECTION_AREA.CURR_ROW = -1;
578 								SELECTION_AREA.START_ROW++;
579 								if(SELECTION_AREA.CURR_ROW!=-1) 
580 									SELECTION_AREA.CURR_ROW++;
581 								SELECTION_AREA.START_COL++;
582 								SELECTION_AREA.CURR_COL++;
583 								
584 								var newGroupId = require('NexcelUI').addGroup(newName , WorkBook.ACTIVE_SHEET_ID, SELECTION_AREA, showColumnName, getHeader(),  extendToLastRow, showGroupTitle);
585 								if(newGroupId){
586 									//showSuccess('Group "'+newName+'" created successfully.');
587 									WorkBook.MDI.addWorkBookMDI.close();
588 									WorkBook.MDI.addWorkBookMDI = null;
589 									return; 
590 								}
591 							}else{
592 								if(require('NexcelGroupList').getGroupObjByName(newName)){
593 									modal({
594 										type  : 'alert',
595 										title : 'Warning! The group name already exists',
596 										text  : newName+" - The group name already exists."
597 									});
598 									return;
599 								}
600 								require('NexcelUI').renameGroup(oldName, newName, showColumnName, getHeader());
601 								var msg = 'Group "'+newName+'" renamed successfully.';
602 								$('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span id="errorMessage"><strong>Success ! </strong> '+msg+'</span>		</div>').appendTo($(CONTENT).find('#messageDiv'));
603 								$(CONTENT).find('#messageDiv').show();
604 								$($(CONTENT).parent().find('button')[1]).html("Close");
605 								$($(CONTENT).parent().find('button')[2]).hide();
606 								var groupObj = require('NexcelGroupList').getGroupObjByName(newName);
607 								groupObj.name = newName;
608 								$($('#groupNameDiv'+groupObj.id).find('.Title P')[0]).html(newName);
609 								//Update all the dependency ranges with new name.
610 								require(['RenameFactController'],function(renameFactController){
611 									var cellFormulaList = require('NexcelCellList').getListOfCellWithFormula();
612 									var groupObjList = require('NexcelGroupList').getGroupObjListOnWorkBook();
613 									var renameFactController = require('RenameFactController');
614 									var groupObj = require('NexcelGroupList').getGroupObjByName(newName);
615 									var oldheaderList = groupObj.colNameList;
616 									groupObj.colNameList = getHeader();
617 									groupObj.colNameAvailable = showColumnName;
618 									var header = $.map( oldheaderList, function( n ) {
619 													  return n.name;
620 													});
621 									if(groupObj.colNameList.length>oldheaderList.length){
622 										var diff = groupObj.colNameList.length - oldheaderList.length;
623 										for(var i=0; i<diff; i++)
624 											header.push('TempVar'+i);
625 									}else
626 										header = undefined;
627 									
628 									for (var i = 0; i < groupObjList.size(); i++) {
629 										var groupObj = groupObjList.get(i); 
630 										if (!groupObj.formula || groupObj.formula.indexOf(oldName)<0) {
631 											continue;
632 										}
633 										//new code start here
634 										
635 										groupObj.formula = renameFactController.getRenamedFormula(groupObj.formula, oldName, newName, header);
636 										require('NexcelUIDataService').updateGroupFormula(groupObj.id, groupObj.formula);
637 									}
638 									var updatedCellList = require('Collections').ArrayList();
639 									for (var i = 0; i < cellFormulaList.size(); i++) {
640 										var cellObj = cellFormulaList.get(i);
641 										if(cellObj.getFormula().indexOf(oldName)<0)
642 											continue;
643 										require('ParsingController').parseFormula(cellObj.getFormula());
644 										var newFormula = renameFactController.getRenamedFormula(cellObj.getFormula(), oldName, newName, header);
645 										cellObj.setFormula("="+newFormula);
646 										updatedCellList.add(cellObj);
647 									}
648 									require(['WorkBookDataService'],function(workBookDataService){
649 										workBookDataService.updateListOfCells(updatedCellList.json());	
650 									});
651 								});
652 							}
653 				        }
654 				    }
655 				];
656 				/**
657 				 *	Function to do action on Column Name check box is clicked. 
658 				 */
659 				var columnNameCBAction = function(){
660 					$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv')).find('div.input-group').remove();
661 					var checked = $($(require('WorkBook').MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).is(':checked');
662 					if (checked) {
663 						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv').show();
664 						if($("input[name=inputType]:checked").val() == "RANGE"){
665 							var ranges = $(WorkBook.MDI.addWorkBookMDI.content[0]).find('#rangeValueTxt').val();
666 								ranges = ranges.split(':');
667 							if(ranges.length!=2){
668 								$('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <span id="errorMessage"><strong>Success ! </strong> '+msg+'</span>		</div>').appendTo($(CONTENT).find('#messageDiv'));
669 								$(WorkBook.MDI.addWorkBookMDI.content[0]).find('#messageDiv').show();
670 								return;
671 							}
672 							var GridView = require('GridView');
673 							var startLoc = GridView.parseLocation(ranges[0]);
674 							var endLoc = GridView.parseLocation(ranges[1]);
675 							var columnSize =  endLoc.col - startLoc.col +1;
676 							for(var i=0; i<columnSize; i++){
677 								var txt = $('<div class="input-group margin-bottom-sm"><span class="input-group-addon" id="column1"><i class="fa fa-columns fa-fw"></i></span>  <input class="form-control input-sm" type="text" placeholder="Column '+(i+1)+'"></div>').appendTo($(WorkBook.MDI.addWorkBookMDI.content[0]).find('.column-names-list'));
678 							}
679 						}else{
680 							
681 							if(renameGroup){
682 								var groupObj = require('NexcelGroupList').getGroupObjByName(oldName);
683 								var groupData =  require('NexcelUI').GROUP.DATA.getGroupData(oldName);
684 								for(var i=0; i<parseInt(groupObj.colSize); i++){
685 									var colName="";
686 									if(groupObj.colNameAvailable){
687 										if(groupObj.colNameList){
688 											try{
689 												colName = groupObj.colNameList[i].name;	
690 											}catch(e){
691 												colName='';
692 											}
693 										}else if(groupData)
694 											colName = groupData[0][i];
695 									}
696 									var txt = $('<div class="input-group margin-bottom-sm"><span class="input-group-addon" id="column1"><i class="fa fa-columns fa-fw"></i></span>  <input class="form-control input-sm" type="text" value='+colName+' placeholder="Column '+(i+1)+'"></div>').appendTo($(WorkBook.MDI.addWorkBookMDI.content[0]).find('.column-names-list'));
697 									$($(txt).find('input')[0]).bind('keypress', function (event) {
698 												    var regex = new RegExp("[a-zA-Z0-9_]+");
699 												    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
700 												    if (!regex.test(key)) {
701 												       event.preventDefault();
702 												       return false;
703 												    }
704 											   });
705 								}
706 							}else{
707 								var selectionArea = require('MouseListener').getOrderedSelectionPos(HANDLER.SELECTION_HANDLER);
708 								if(selectionArea.START_COL >=0   && selectionArea.CURR_COL >=0){
709 									var columnSize =  selectionArea.CURR_COL - selectionArea.START_COL +1;
710 									for(var i=0; i<columnSize; i++){
711 										var txt = $('<div class="input-group margin-bottom-sm"><span class="input-group-addon" id="column1"><i class="fa fa-columns fa-fw"></i></span>  <input class="form-control input-sm" type="text" placeholder="Column '+(i+1)+'"></div>').appendTo($(WorkBook.MDI.addWorkBookMDI.content[0]).find('.column-names-list'));
712 										$($(txt).find('input')[0]).bind('keypress', function (event) {
713 												    var regex = new RegExp("[a-zA-Z0-9_]+");
714 												    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
715 												    if (!regex.test(key)) {
716 												       event.preventDefault();
717 												       return false;
718 												    }
719 											   });
720 									}
721 								}
722 							}
723 						}
724 					} else{
725 						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv').hide();
726 					}
727 				};
728 				var addWorkBookModalSetup = function(){
729 					
730 					$(WorkBook.MDI.addWorkBookMDI.content[0]).find('#rangeValueDiv').hide();
731 					$(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv').hide();
732 					$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#withSelectionRadio')[0]).change(function(){
733 													           						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('#rangeValueDiv').hide();
734 													           						$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv')).find('div.input-group').remove();
735 													           						$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).attr('checked',false);
736 													           						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv').hide();
737 													           					});
738 					$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#withRangeRadio')[0]).change(function(){
739 													           						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('#rangeValueDiv').show();
740 													           						$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).attr('checked',false);
741 													           						$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv')).find('div.input-group').remove();
742 													           						$(WorkBook.MDI.addWorkBookMDI.content[0]).find('div.columnNamesDiv').hide();
743 													           					});	
744 					if(renameGroup){
745 						$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#groupName')).val(oldName);
746 						var groupObj = require('NexcelGroupList').getGroupObjByName(oldName);
747 						if(groupObj.colNameAvailable){
748 							$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).attr('checked',true);
749 						}else
750 							$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).attr('checked',false);
751 						if(groupObj.groupTitle){
752 							$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#showGroupTitleCB')[0]).attr('checked',true);
753 						}else
754 							$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#showGroupTitleCB')[0]).attr('checked',false);
755 						
756 					}	
757 					$($(WorkBook.MDI.addWorkBookMDI.content[0]).find('#columnNameCB')[0]).click(function(){
758 						columnNameCBAction();
759 					});
760 					columnNameCBAction();	
761 				};
762 				
763 			   	WorkBook.MDI.addWorkBookMDI = $.jsPanel({
764 				    selector: "#jspanel-func .panel-body",
765 				    title:    "Create Group",
766 				    toolbarFooter : arr,
767 				    modal: true,
768 				    position: "center",
769 				    resizable: {
770 			            minWidth: 400,
771 			            minHeight: 300
772 			        },
773 			        load: {
774 				        url: 'assets/include/modal/CreateGroup.html',
775 				        complete : function(){
776 				        	addWorkBookModalSetup();
777 				        }
778 				    },
779 				    overflow: {vertical: 'scroll'},
780 				    size:     { width: 550, height: 300 },
781 				    callback: [
782 				        function(panel){
783 				           	//require('GridView').jsPanelTipsy();
784 				        }
785 				    ]
786 				});
787 			},
788 
789 			/**
790 			 * @name editGroup
791 			 * @memberOf contextmenu.ACTION
792 			 * @method 
793 			 * @description Action to edit a group where the event happened, which is recorded in the contextmenu.EVENT_TARGET, It calls contextmenu.openCreateGroupModal to setup the MDI.
794 			 * @function
795 			 */
796 			editGroup:function () {
797 				if(require('contextmenu').EVENT_TARGET.length > 1){
798 					modal({
799 						type  : 'alert',
800 						title : 'Warning! Cannot rename multiple groups',
801 						text  : "The selected cell is a part of multiple groups, please select a cell unique to this group."
802 					});
803 					return false;	
804 				}
805 				
806 				var groupObj = require('contextmenu').EVENT_TARGET[0];
807 				var RENAME_GROUP = true;
808 				this.openCreateGroupModal(RENAME_GROUP, groupObj.name);
809 			},
810 			/**
811 			 * @name deleteGroup
812 			 * @memberOf contextmenu.ACTION
813 			 * @method 
814 			 * @description Action to delete a group where the event happened, which is recorded in the contextmenu.EVENT_TARGET, It calls nexcelUI.deleteGroup to delete.
815 			 * @function
816 			 */
817 			deleteGroup:function () {
818 				if(require('contextmenu').EVENT_TARGET.length > 1){
819 					modal({
820 						type  : 'alert',
821 						title : 'Warning! Cannot delete multiple groups',
822 						text  : "The selected cell is a part of multiple groups, please select a cell unique to this group."
823 					});
824 					return false;	
825 				}
826 				var groupObj = require('contextmenu').EVENT_TARGET[0];
827 				
828 				modal({
829 					type  : 'confirm',
830 					title : 'Confirm',
831 					text  : 'Do you want to Delete '+groupObj.name+' ?',
832 					callback: function(result){ 
833 							if(result){
834 								if(require('NexcelUI').deleteGroup(groupObj)){
835 									require('GridView').removeStyleToGroupTitleAndColName(groupObj);
836 									require('GridView').clearGroupTitleAndColNameCellValues(groupObj);
837 								}
838 							} 
839 						}
840 				});
841 			},
842 			
843 			/**
844 			 * @name viewEvaluationGraph
845 			 * @memberOf contextmenu.ACTION
846 			 * @method 
847 			 * @description Action to show the evaluation Graph with the fromula associated with EVENT_TARGET group.
848 			 * @function
849 			 */
850 			viewEvaluationGraph:function(){
851 				var groupObj = require('contextmenu').EVENT_TARGET[0];
852 				require(['GraphController'],function(graphController){
853 					graphController.showEvaluationGraph(groupObj.formula);	
854 				});
855 			}
856 		}
857 	
858 	};
859 });
860