Copyright (c) 2005-2006 Tremend Software Consulting, Licensed under the Academic Free License version 2.1 or BSD licenses
*/
dojo.provide("dojox.widget.iSpread");
dojo.provide("dojox.widget.iSpreadSheet");
/** * Create toolbar, tabcontainer and first sheet */postCreate:function(args,frag){this.createToolbar();this.createTabContainer();this.createSheet("sheet 1");},button:function(iconClass){returnnewdijit.form.Button({label:"button",showLabel:false,iconClass:iconClass});},/** * Initializes the toolbar */createToolbar:function(){tb=newdijit.Toolbar();this.domNode.appendChild(tb.domNode);tb.addChild(this.button(this.img("justifyleft")));tb.addChild(this.button(this.img("justifycenter")));tb.addChild(this.button(this.img("justifyright")));tb.addChild(this.button(this.img("justifyfull")));this.fontMenu=newdijit.form.Select({name:"formatBlock",options:[ {label: "Font", value: "-1"}, {label: "Serif", value: "serif"}, {label: "Sans-serif", value: "sans-serif"}, {label: "Cursive", value: "cursive"}, {label: "Fantasy", value: "fantasy"}, {label: "Monospace", value: "monospace"}]});dojo.connect(this.fontMenu,"onChange",this,"changeFont");//this.fontMenu.domNode.getElementsByTagName("select")[0].style.width="80px";tb.addChild(this.fontMenu);//fontsizemenuthis.fontSizeMenu=newdijit.form.Select({name:"formatBlock",options:[ {label: "Size", value: "-1"}, {label: "10", value : "10"}, {label: "12", value : "12"}, {label: "14", value : "14"}, {label: "16", value : "16"}, {label: "18", value : "18"}, {label: "24", value : "24"}, {label: "32", value : "32"}, {label: "40", value : "40"}]});dojo.connect(this.fontSizeMenu,"onChange",this,"changeFontSize");//this.fontSizeMenu.domNode.style.width="55px";tb.addChild(this.fontSizeMenu);//separatortb.addChild(newdijit.ToolbarSeparator());//boldtogglebuttonthis.boldItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("bold")});dojo.connect(this.boldItem,"onClick",this,"makeBold");tb.addChild(this.boldItem);//italictogglebuttonthis.italicItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("italic")});dojo.connect(this.italicItem,"onClick",this,"makeItalic");tb.addChild(this.italicItem);//underlinetogglebuttonthis.underlineItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("underline")});dojo.connect(this.underlineItem,"onClick",this,"makeUnderline");tb.addChild(this.underlineItem);//separatortb.addChild(newdijit.ToolbarSeparator());//colordialogvarpalette=newdijit.ColorPalette({palette:"3x4",style:"display: none"});this.colorItem=newdijit.form.DropDownButton({iconClass:this.img("forecolor"),dropDown:palette});this.colorItem.colorPalette=palette;dojo.connect(this.colorItem.colorPalette,"onChange",this,"changeColor");tb.addChild(this.colorItem);//bgcolordialogpalette=newdijit.ColorPalette({palette:"3x4",style:"display: none"});this.bgcolorItem=newdijit.form.DropDownButton({iconClass:this.img("backcolor"),dropDown:palette});this.bgcolorItem.bgcolorPalette=palette;dojo.connect(this.bgcolorItem.bgcolorPalette,"onChange",this,"changeBGColor");tb.addChild(this.bgcolorItem);//sheetmenuthis.sheetMenu=newdijit.form.Select({name:"sheetMenu",options:[ {label: "Sheet", value : "-1"}, {label: "Rename", value : "1"}, {label: "Delete", value : "2"}, {label: "New", value : "3"}]});dojo.connect(this.sheetMenu,"onChange",this,"sheetAction");//this.sheetMenu.domNode.style.width="65px";tb.addChild(this.sheetMenu);//functionsmenuthis.functionsMenu=newdijit.form.Select({name:"functionsMenu",options:[ {label: "Functions", value : "-1"}, {label: "Sum", value: "sum"}, {label: "Product", value : "product"}, {label: "Average", value : "avg"}, {label: "Min", value : "min"}, {label: "Max", value : "max"}, {label: "Count", value: "count"}]});dojo.connect(this.functionsMenu,"onChange",this,"applyFunction");//this.functionsMenu.domNode.style.width="85px";tb.addChild(this.functionsMenu);},/** * Util function. The same as the one in test_toolbar.html. Returns the image from src/widget/spreadsheet/templates/buttons * @param name the name of image (no extension) */img:function(name){returnthis.iconMap[name]+" toolbarButton";},/** * Creates the tab container which will hold the sheets */createTabContainer:function(){this.tabContainer=newdijit.layout.TabContainer({style:"height: 100%; width: 100%;",tabPosition:"bottom"});this.domNode.appendChild(this.tabContainer.domNode);dojo.connect(this.tabContainer,"selectChild",this,"tabChanged");this.tabContainer.startup();},/** * Callback for row menu * @param val the value for the item selected */rowAction:function(val){if(val!="-1"){switch(val){case"1"://insertrowbeforethis.tabs[this.activeTab].sheet.insertRowBefore();break;case"2"://insertrowbeforethis.tabs[this.activeTab].sheet.insertRowAfter();break;case"3"://insertrowbeforethis.tabs[this.activeTab].sheet.removeRows();break;}this.setSelectIndex(this.rowsMenu,0);}},/** * Callback for column menu * @param val the value for the item selected */colAction:function(val){if(val!="-1"){switch(val){case"1"://insertrowbeforethis.tabs[this.activeTab].sheet.insertColumnBefore();break;case"2"://insertrowbeforethis.tabs[this.activeTab].sheet.insertColumnAfter();break;case"3"://insertrowbeforethis.tabs[this.activeTab].sheet.removeCols();break;}this.setSelectIndex(this.rowsMenu,0);}},/** * Callback for sheet menu * @param val the value for the item selected */sheetAction:function(val){if(val!="-1"){switch(val){case"1"://renamecurrentsheetvarnewVal=prompt("Enter the new name for the sheet");if(newVal){this.tabs[this.activeTab].attr("title",newVal);this.tabs[this.activeTab].label=newVal;}break;case"2"://deletecurrentsheetthis.removeCurrentSheet();break;case"3"://newsheetthis.createSheet("sheet "+(this.tabs.length+1));break;}this.setSelectIndex(this.sheetMenu,0);}},setSelectIndex:function(select,index){varoptions=select.getOptions();if(options&&options.length&&options[index])select.attr("value",options[index].value);},/** * Applies a formula * @param val the value for the item selected */applyFunction:function(val){if(this.functionsMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.applyFormula(this.functionsMenu.attr("value"));}},/** * Callback for font size menu */changeFontSize:function(e){if(this.fontSizeMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.FONT_SIZE,this.fontSizeMenu.attr("value"));this.setSelectIndex(this.fontSizeMenu,0);}},/** * Callback for font size menu */changeFont:function(e){if(this.fontMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.FONT,this.fontMenu.attr("value"));this.setSelectIndex(this.fontMenu,0);}},/** * Callback for color picker */changeColor:function(color){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.COLOR,this.colorItem.colorPalette.attr("value"));},/** * Callback for background color picker */changeBGColor:function(e){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.BG_COLOR,this.bgcolorItem.bgcolorPalette.attr("value"));},/** * Callback for bold button */makeBold:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.BOLD,this.boldItem.attr("checked"));},/** * Callback for italic button */makeItalic:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.ITALIC,this.italicItem.attr("checked"));},/** * Callback for underline button */makeUnderline:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.UNDERLINE,this.underlineItem.attr("checked"));},/** * Creates a new sheet (new ContentPane and a new sheet inside) * @param name the name of the sheet */createSheet:function(sheetName){//createthecontentpaneforthenewtabforthisnewsheetvarcurrentTabIdx=this.tabs.length;this.tabs[currentTabIdx]=newdijit.layout.ContentPane({id:"sheet"+currentTabIdx,title:sheetName});this.tabContainer.addChild(this.tabs[currentTabIdx]);//calledonce(otherwisetheselectiongetsbrokenthis.tabContainer.selectChild(this.tabs[currentTabIdx]);varv=newdojox.widget.iSpreadSheet();v.init(this.tabs[currentTabIdx]);this.tabs[currentTabIdx].sheet=v;this.activeTab=currentTabIdx;//secondcallisnecessary,sincesomepropsaresetbeforethiscallthis.tabContainer.selectChild(this.tabs[currentTabIdx]);//toolbartogglebuttonsneedtobenotifiedsothattheyreflectthestate//ofthecell(ifcellhasboldstyle,boldbuttonmustbetoggled)dojo.connect(v,"setFormatting",this,"setFormatting");},/** * Event handler for "setFormatting" event thrown by the sheet object. This is useful for chaning button states * according to cell's formatting. If one cell has bold style, the toolbar should reflect this state * * @param spreadsheet the sheet that triggered the event * @param _bold true if bold enabled, false otherwise * @param _italic true if italic enabled, false otherwise * @param _underline true if underline enabled, false otherwise */setFormatting:function(spreadsheet,_bold,_italic,_underline){//this.boldItem.setSelected(_bold);this.boldItem.attr("checked",_bold);//this.italicItem.setSelected(_italic);this.italicItem.attr("checked",_italic);//this.underlineItem.setSelected(_underline);this.underlineItem.attr("checked",_underline);},/** * Removes the current working sheet */removeCurrentSheet:function(){if(this.tabs.length>1){this.tabContainer.removeChild(this.tabs[this.activeTab]);for(vari=this.activeTab;i<this.tabs.length-1;i++){this.tabs[i]=this.tabs[i+1];}this.tabs.length--;this.activeTab=this.activeTab>0?this.activeTab-1:this.activeTab;}else{alert("The document must have at least one sheet");}},/** * Handles sheet change. This is needed for the sheet to decouple certain events that may mess up how sheet receive events */tabChanged:function(){for(vari=0;i<this.tabs.length;i++){if(this.tabs[i]==this.tabContainer.selectedTabWidget){this.activeTab=i;if(this.tabs[i].sheet){this.tabs[i].sheet.gainFocus();}}else{if(this.tabs[i].sheet){this.tabs[i].sheet.loseFocus();}}}}}
/***Regularexpressionsfordetectingcellintervals,cellsorfunctions*/reInterval:/[a-zA-Z]{1}[0-9]+:[a-zA-Z]{1}[0-9]+/g,reCell:/[^a-zA-Z]{1}[a-zA-Z]{1}[0-9]+/g,reFunction:/[a-zA-Z]{3,}[a-zA-Z0-9]*\(/g,/***Fordetectingcirculardependencies,thespreadsheetwillberepresentedasa*directedgraph*Thegraphisrepresentedasamatrixinwhichavalueof1meansthere's a direct dependency*betweennodeAandnodeB.Forexample,ifA->B,A->C,B->D,B->E,D->C,C->B,thegraphwilllooklike:*ABCDE*__________*A|01100*B|00011*C|01000*D|00100*E|00000*/ssGraph:null,/***Thisobjectwillholdamapwithcorrespondencesbtwcellnotationandnumberinmatrix*(A1-0,A2-1,A3-2...,B15-20)*/cellGraphLookup:null,domNode:null,/****/months:["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],reDate1:/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,4}/,reDate2:/[0-9]{1,2}-[a-z]{3}-[0-9]{4}/,reNumber1:/[^0-9e\.]/,getCursorPosition:function(e){e=e||window.event;varcursor={x:0,y:0};if(e.pageX||e.pageY){cursor.x=e.pageX;cursor.y=e.pageY;}else{varde=dojo.doc.documentElement;vardb=dojo.body;cursor.x=e.clientX+((de||db)["scrollLeft"])-((de||db)["clientLeft"]);cursor.y=e.clientY+((de||db)["scrollTop"])-((de||db)["clientTop"]);}returncursor;},postCreate:function(){},/***Initializesthegraphicwidget(table,column/rowheaders,etc)*@paramcontentPanetheContentPaneobjectcorrespondingtoatabinaTabContainer*/init:function(contentPane){this.domNode=contentPane.domNode;//createthetableforthissheetthis.createSpreadsheetCells(contentPane);this.resetSpreadsheet();this.initGraph();//disableselection//dojo.html.disableSelection(this.domNode);dojo.setSelectable(this.domNode,false);this.gainFocus();this.createInputElem();this._focus(this.currentFocusedCol,this.currentFocusedRow);//browserdetectionthis.isIE=/msie/i.test(navigator.userAgent);this.isChrome=/chrome/i.test(navigator.userAgent);},/***Calledwhenasheetislosingfocus(othersheetbecomesactive)-disconnectseventhandlers*/loseFocus:function(){//dojo.event.disconnect(this.domNode,"onmousedown",this,"onMouseDown");dojo.disconnect(this.domNode,"onmousedown",this,"onMouseDown");//dojo.event.disconnect(this.domNode,"onmousemove",this,"onMouseMove");dojo.disconnect(this.domNode,"onmousemove",this,"onMouseMove");//dojo.event.disconnect(this.domNode,"onmouseup",this,"onMouseUp");dojo.disconnect(this.domNode,"onmouseup",this,"onMouseUp");//dojo.event.disconnect(this.domNode,"onmouseover",this,"onMouseOver");dojo.disconnect(this.domNode,"onmouseover",this,"onMouseOver");//dojo.event.disconnect(document,"onkeypress",this,"onKeyPress");dojo.disconnect(document,"onkeypress",this,"onKeyPress");//dojo.event.disconnect(document,"onkeyup",this,"onKeyUp");dojo.disconnect(document,"onkeyup",this,"onKeyUp");//dojo.event.disconnect(this.domNode,"ondblclick",this,"onDblClick");dojo.disconnect(this.domNode,"ondblclick",this,"onDblClick");},/***Calledwhenasheetisgainingfocus-reconnectseventhandlers*/gainFocus:function(){//makesureeventsarenotconnectedtwicethis.loseFocus();//dojo.event.connect(this.domNode,"onmousedown",this,"onMouseDown");dojo.connect(this.domNode,"onmousedown",this,"onMouseDown");//dojo.event.connect(this.domNode,"onmousemove",this,"onMouseMove");dojo.connect(this.domNode,"onmousemove",this,"onMouseMove");//dojo.event.connect(this.domNode,"onmouseup",this,"onMouseUp");dojo.connect(this.domNode,"onmouseup",this,"onMouseUp");//dojo.event.connect(this.domNode,"onmouseover",this,"onMouseOver");dojo.connect(this.domNode,"onmouseover",this,"onMouseOver");//dojo.event.connect(document,"onkeypress",this,"onKeyPress");dojo.connect(document,"onkeypress",this,"onKeyPress");//dojo.event.connect(document,"onkeyup",this,"onKeyUp");dojo.connect(document,"onkeyup",this,"onKeyUp");//dojo.event.connect(this.domNode,"ondblclick",this,"onDblClick");dojo.connect(this.domNode,"ondblclick",this,"onDblClick");},/***Createsthespreadsheetcells(theactual<TABLE>element)*@paramcontentPanetheContentPaneobjectassociatedwithaTabContainer*/createSpreadsheetCells:function(contentPane){varhtml='';html+='<div style="height:100%;width:100%;overflow:auto;">';html+='<table class="sheet" cellspacing="0" cellpadding="0" >';html+=' <thead>';html+=' <th class="sheetRow1stCell"></th>';for(varcol=0;col<10;col++){html+=' <th><div class="header"><div class="headerText">A</div><div class="horizontalResizer"> </div></div></th>';}html+=' </thead>';html+=' <tbody>';for(varrow=0;row<20;row++){html+=' <tr>';html+=' <td class="sheetRow1stCell"><div><div class="rowHeaderText"></div><div class="verticalResizer"> </div></div></td>';for(varcol=0;col<10;col++){html+=' <td class="sheetCell"><div class="sheetCellContent"></div></td>';}html+=' </tr>';}html+=' </tbody>';html+='</table>';html+='</div>';contentPane.attr("content",html);},/***Initializesthedependenciesgraph*/initGraph:function(){this.spreadsheetWidth=this.rows[0].cells.length-1;this.spreadsheetHeight=dojo.isIE?(this.rows.length-1):this.rows.length;this.ssGraph=newArray();//initializethegraphedgesvarnumNodes=this.spreadsheetWidth*this.spreadsheetHeight;for(vari=0;i<numNodes;i++){this.ssGraph[i]=newArray();for(varj=0;j<numNodes;j++){this.ssGraph[i][j]=0;}}//populatethelookupthis.cellGraphLookup=newObject();for(vari=0;i<this.spreadsheetWidth;i++){for(varj=1;j<=this.spreadsheetHeight;j++){this.cellGraphLookup[String.fromCharCode("A".charCodeAt(0)+i)+j]=j*this.spreadsheetWidth+i;}}},/***Applieslabelstocolumn/rowheaders.Fixeswidthoffirstcolumnandinitializesinternaldataforeachcell/header*/resetSpreadsheet:function(){this.tbody=this.domNode.getElementsByTagName("tbody")[0];this.rows=this.tbody.getElementsByTagName("tr");for(vari=0;i<this.rows.length;i++){//-notdiscoveredyet-forsomereasonsFFthrowssomeerrorswhenusingfirstChild.firstChild//if(this.rows[i].cells[0].firstChild&&this.rows[i].cells[0].firstChild.firstChild){this.rows[i].cells[0].firstChild.firstChild.innerHTML=""+(i+1);//}//[D]this.rows[i].dHeight=dojo.html.getInnerHeight(this.rows[i]);this.rows[i].dHeight=dojo.position(this.rows[i]).h;for(varj=0;j<this.rows[i].cells.length;j++){//[D]vartmpW=dojo.html.getInnerWidth(this.rows[i].cells[j].firstChild)+(dojo.render.html.ie?2:3);vartmpW=dojo.position(this.rows[i].cells[j].firstChild).w+(dojo.isIE?2:3);//[D]vartmpH=dojo.html.getInnerHeight(this.rows[i].cells[j].firstChild)+(dojo.render.html.ie?3:3);vartmpH=dojo.position(this.rows[i].cells[j].firstChild).h+(dojo.isIE?3:3);this.rows[i].cells[j].firstChild.dWidth=tmpW;this.rows[i].cells[j].firstChild.style.width=tmpW;this.rows[i].cells[j].firstChild.dHeight=tmpH;this.rows[i].cells[j].firstChild.style.height=tmpH;//varbgColor=dojo.html.getBackgroundColor(this.rows[i].cells[j].firstChild);varbgColor=dojo.style(this.rows[i].cells[j].firstChild,"backgroundColor");//[D]this.rows[i].cells[j].firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);this.rows[i].cells[j].firstChild.dBackgroundColor=bgColor;//dojo.html.disableSelection(this.rows[i].cells[j]);dojo.setSelectable(this.rows[i].cells[j],false);//dojo.html.disableSelection(this.rows[i].cells[j].firstChild);dojo.setSelectable(this.rows[i].cells[j].firstChild,false);}varcucu=this.rows[i].cells[0].getElementsByTagName("div");for(varss=0;ss<cucu.length;ss++){cucu[ss].style.width="20px";}this.rows[i].cells[0].style.width="20px";this.rows[i].cells[0].firstChild.style.height="20px";this.rows[i].cells[0].firstChild.firstChild.style.height="18px";this.rows[i].cells[0].firstChild.firstChild.nextSibling.style.height="2px";}varths=this.domNode.getElementsByTagName("TH");ths[0].style.width="20px";for(vari=1;i<ths.length;i++){ths[i].dCellIndex=i-1;//[D]ths[i].dWidth=dojo.html.getInnerWidth(ths[i]);ths[i].dWidth=dojo.position(ths[i]).w;if(ths[i].firstChild&&ths[i].firstChild.firstChild){ths[i].firstChild.firstChild.innerHTML=String.fromCharCode("A".charCodeAt(0)+i-1);}dojo.setSelectable(ths[i],false);dojo.setSelectable(ths[i].firstChild,false);dojo.setSelectable(ths[i].firstChild.firstChild,false);}},/***Createstheinputelementtodisplaywheneditingacell*/createInputElem:function(){if(this.inputElem==null){this.inputElem=document.createElement("input");with(this.inputElem){type="text";className="sheetInput";style.position="absolute";style.display="none";tdElem=null;}document.body.appendChild(this.inputElem);dojo.setSelectable(this.inputElem,false);}},/***Handlesonmousedownwhichcancauseseveralrelevanteventsforspreadsheet:focusing,selection,resizing*/onMouseDown:function(e){this.debug("[onMouseDown]");vartarget=(e.target)?e.target:e.srcElement;//[D]varinputElem=dojo.html.getParentByType(e.target,"INPUT");varinputElem=dijit.range.getAncestor(target,/INPUT/i);if(inputElem&&dojo.hasClass(inputElem,"sheetInput")){return;}this.deselectAll();//[D]varcurrentTDElem=dojo.html.getParentByType(e.target,"TD");varcurrentTDElem=dijit.range.getAncestor(target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.isSelectingCells=true;this.selectionStartCell=currentTDElem;this.selectCellByTD(this.selectionStartCell,true);e.preventDefault();}//[D]varcurrentDIVElem=dojo.html.getParentByType(e.target,"DIV");varcurrentDIVElem=dijit.range.getAncestor(target,/DIV/i);if(currentDIVElem&&dojo.hasClass(currentDIVElem,"horizontalResizer")){this.isResizingHorizontal=true;varpos=this.getCursorPosition(e);this.resizeOrigXPos=pos.x;//[D]this.resizeOrigTH=dojo.html.getParentByType(e.target,"TH");this.resizeOrigTH=dijit.range.getAncestor(target,/TH/i);}if(currentDIVElem&&dojo.hasClass(currentDIVElem,"verticalResizer")){this.isResizingVertical=true;varpos=this.getCursorPosition(e);this.resizeOrigYPos=pos.y;//[D]this.resizeOrigTD=dojo.html.getParentByType(e.target,"TD");this.resizeOrigTD=dijit.range.getAncestor(target,/TD/i);}if(!this.isResizingHorizontal&&!this.isResizingVertical){//[D]varcurrentTH=dojo.html.getParentByType(e.target,"TH");varcurrentTH=dijit.range.getAncestor(target,/TH/i);if(currentTH){this.isSelectingColumns=true;this.selectionStartColumn=currentTH.dCellIndex;this.selectColumns(this.selectionStartColumn);}//[D]varcurrentTDRowHeader=dojo.html.getParentByType(e.target,"TD");varcurrentTDRowHeader=dijit.range.getAncestor(target,/TD/i);if(currentTDRowHeader&&dojo.hasClass(currentTDRowHeader,"sheetRow1stCell")){this.isSelectingRows=true;this.selectionStartRow=this.getCellRow(currentTDRowHeader);this.selectRows(this.selectionStartRow);}}this.debug("[onMouseDown]");},/***Handlesonmousemove-usefulwhenresizingtodinamicallyresizeasmousemoves*/onMouseMove:function(e){this.debug("[onMouseMove]");if(this.isResizingHorizontal){this.resizeCol(e,false);}if(this.isResizingVertical){this.resizeRow(e,false);}this.debug("[/onMouseMove]");},/***Handlesonmouseover-tokeeptrackoftheselectionprocess*/onMouseOver:function(e){this.debug("[onMouseOver]");if(this.isSelectingCells){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.deselectAll();varsCol=this.getCellCol(this.selectionStartCell);varsRow=this.getCellRow(this.selectionStartCell);varcCol=this.getCellCol(currentTDElem);varcRow=this.getCellRow(currentTDElem);this.debug("isSelectingCells[c{0},r{1},c{2},r{3}]".format(sCol,sRow,cCol,cRow));this.selectRegion(cCol,sCol,cRow,sRow,true);}}if(this.isSelectingColumns){//themousemaymoveoverTHsorTDs.HoweverweshoulddetectineachcasethecolumnvarcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){varselectionEndColumn=this.getCellCol(currentTDElem);this.selectColumns(selectionEndColumn);}else{varcurrentTHElem=dijit.range.getAncestor(e.target,/TH/i);if(currentTHElem){varselectionEndColumn=currentTHElem.dCellIndex;this.selectColumns(selectionEndColumn);}}}if(this.isSelectingRows){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&(dojo.hasClass(currentTDElem,"sheetCell")||dojo.hasClass(currentTDElem,"sheetRow1stCell"))){varselectionEndRow=this.getCellRow(currentTDElem);this.selectRows(selectionEndRow);}}this.debug("[/onMouseOver]");},/***Handlesonmouseup-eitherselectionofresizinghavefinished*/onMouseUp:function(e){this.debug("[onMouseUp]");if(this.isSelectingCells){//unselectonlyifthemouseupoccuredonthesamecellif(this.selectionStartCell&&this.selectionStartCell==dijit.range.getAncestor(e.target,/TD/i)){this.selectCellByTD(this.selectionStartCell,false);this.focusOn(this.selectionStartCell);}this.isSelectingCells=false;}if(this.isResizingHorizontal){this.resizeCol(e,true);this.isResizingHorizontal=false;}if(this.isResizingVertical){this.resizeRow(e,true);this.isResizingVertical=false;}if(this.isSelectingColumns){this.isSelectingColumns=false;}if(this.isSelectingRows){this.isSelectingRows=false;}this.debug("[onMouseUp]");},/***Ondblclick-theeditingboxisshown*/onDblClick:function(e){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.deselectAll();this.showInputOverTD(currentTDElem);}},/***Onkeypress-managesdelete,enter,backspace,esc,spacekeys*/onKeyPress:function(e){varkeyCode=e.keyCode==0?e.which:e.keyCode;vark=dojo.keys;varkeyHandled=false;if(keyCode==k.KEY_ESCAPE){this.hideInput(true);keyHandled=true;}if(keyCode==k.KEY_BACKSPACE){this.eraseCurrentCellContent();}if(keyCode==k.KEY_DELETE){this.eraseCurrentCellContent();}if(keyCode==k.KEY_ENTER){if(!this.isEditing){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);this.showInputOverTD(tdElem);keyHandled=true;}else{this.moveFocus(0,1);keyHandled=true;}}if(keyCode==k.KEY_SPACE||(keyCode>=41&&keyCode<=44)||keyCode>=47){if(!this.isEditing){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);this.showInputOverTD(tdElem);if(!dojo.isIE){this.inputElem.value=String.fromCharCode(keyCode);}}}if(keyHandled==true){e.preventDefault();e.stopPropagation();}},/***onKeyUp-handlesup/right/down/leftarrows*/onKeyUp:function(e){varkeyCode=e.keyCode==0?e.which:e.keyCode;//vark=dojo.event.browser.keys;vark=dojo.keys;varkeyHandled=false;if(keyCode==k.KEY_DOWN_ARROW){if(!this.isEditing){this.moveFocus(0,1);keyHandled=true;}}if(keyCode==k.KEY_UP_ARROW){if(!this.isEditing){this.moveFocus(0,-1);keyHandled=true;}}if(keyCode==k.KEY_LEFT_ARROW){if(!this.isEditing){this.moveFocus(-1,0);keyHandled=true;}}if(keyCode==k.KEY_RIGHT_ARROW){if(!this.isEditing){this.moveFocus(1,0);keyHandled=true;}}if(keyHandled==true){e.preventDefault();e.stopPropagation();}},/***Movesfocustothespecifiedcell*@deltaXdeltamovementoncolumns*@deltaYdeltamovementonrows*/moveFocus:function(deltaX,deltaY){varnewCol=this.currentFocusedCol;varanyChange=false;if(newCol+deltaX<this.spreadsheetWidth&&newCol+deltaX>=0){newCol=newCol+deltaX;anyChange=true;}varnewRow=this.currentFocusedRow;if(newRow+deltaY<this.spreadsheetHeight&&newRow+deltaY>=0){newRow=newRow+deltaY;anyChange=true;}if(anyChange){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.currentFocusedCol=newCol;this.currentFocusedRow=newRow;this._focus(this.currentFocusedCol,this.currentFocusedRow);}},/***Focusesonagivenelement*@paramelemthe<TD>elementtofocuson*/focusOn:function(elem){var_col=this.getCellCol(elem);var_row=this.getCellRow(elem);if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){this.focusAt(_col,_row);}},/***Focusesatagivenlocation*@param_colthecolcoordinatewheretofocus*@param_rowtherowcoordinatewheretofocus*/focusAt:function(_col,_row){if(_row>=this.spreadsheetHeight){_row=this.spreadsheetHeight-1;}if(_col>=this.spreadsheetWidth){_col=this.spreadsheetWidth-1;}this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.currentFocusedCol=_col;this.currentFocusedRow=_row;this.selectionStartCell=this.getCell(_col,_row);this._focus(this.currentFocusedCol,this.currentFocusedRow);},/***Internalfnwhichactuallydoesthefocusing*@param_colthecolcoordinatewheretofocus*@param_rowtherowcoordinatewheretofocus*/_focus:function(_col,_row){if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){var_tdElem=this.getCell(_col,_row);var_italic=false;var_bold=false;var_underline=false;if(typeof(_tdElem.styleList)!="undefined"){_bold=_tdElem.styleList[this.FORMATTING_TYPES.BOLD]?_tdElem.styleList[this.FORMATTING_TYPES.BOLD]:false;_italic=_tdElem.styleList[this.FORMATTING_TYPES.ITALIC]?_tdElem.styleList[this.FORMATTING_TYPES.ITALIC]:false;_underline=_tdElem.styleList[this.FORMATTING_TYPES.UNDERLINE]?_tdElem.styleList[this.FORMATTING_TYPES.UNDERLINE]:false;}this._fireEvent("setFormatting",_bold,_italic,_underline);varw=_tdElem.firstChild.dWidth;varh=_tdElem.firstChild.dHeight;_tdElem.firstChild.style.width=this.toPx(w-(dojo.isIE?0:4));_tdElem.firstChild.style.height=this.toPx(h-(dojo.isIE?0:4));dojo.addClass(_tdElem.firstChild,"focused");}}},/***Unfocusesthecellatagivenposition*@param_colthecolcoordinatewheretounfocus*@param_rowtherowcoordinatewheretounfocus*/unfocus:function(_col,_row){this.hideInput();if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){var_tdElem=this.getCell(_col,_row);varw=_tdElem.firstChild.dWidth;varh=_tdElem.firstChild.dHeight;_tdElem.firstChild.style.width=this.toPx(w);_tdElem.firstChild.style.height=this.toPx(h);dojo.removeClass(_tdElem.firstChild,"focused");}}},/***Selectsaregionofthespreadsheet*@paramcol1thestartcol*@paramcol2theendcol*@paramrow1thestartrow*@paramrow2theendrow*@param_selectwhethertoselectordeselecttheregion*/selectRegion:function(col1,col2,row1,row2,_select){this.debug("col1={0}, col2={1}, row1={2}, row2={3}, _select={4}".format(col1,col2,row1,row2,_select));varminCol=col1<col2?col1:col2;varmaxCol=col1>col2?col1:col2;varminRow=row1<row2?row1:row2;varmaxRow=row1>row2?row1:row2;this.lastSelectedRegion=[minCol,maxCol,minRow,maxRow];for(vari=minCol;i<=maxCol;i++){for(varj=minRow;j<=maxRow;j++){this.selectCell(i,j,_select);}}if(this.selectionStartCell){this.focusOn(this.selectionStartCell);}if(!_select){this.lastSelectedRegion=null;}},/***SelectsacellgiventheHTMLelement*@param_tdElemthe<TD>elementtoselect*@param_selectwhethertoselectordeselecttheHTMLelement*/selectCellByTD:function(_tdElem,_select){if(typeof(_tdElem)!="undefined"){this.selectCell(this.getCellCol(_tdElem),this.getCellRow(_tdElem),_select);}},/***Selectsordeselectsacell.Selectionmeanschangingthecolortoalighter/darkerbluedependingonB's value (B from RGB)*@param_colthecolumn(0-n,where0correspondstotheAcolumnofthespreadsheetwhichisactuallythesecondcolumnofthetable*@param_rowtherow(0-n,0-correspondssimilarlytorow1)*@param_selectwhethertoselectordeselectthecell*/selectCell:function(_col,_row,_select){if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){vartdElem=this.getCell(_col,_row);if(_select){//varbgColor=dojo.html.getBackgroundColor(tdElem.firstChild);varbgColor=dojo.style(tdElem.firstChild,"backgroundColor");//tdElem.firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//bgColor[0]=parseInt(bgColor[0]);//bgColor[1]=parseInt(bgColor[1]);//bgColor[2]=parseInt(bgColor[2]);//bgColor[0]=bgColor[0]>128?bgColor[0]-32:bgColor[0]+32;//bgColor[1]=bgColor[1]>128?bgColor[1]-32:bgColor[1]+32;//[D]tdElem.firstChild.style.backgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//tdElem.firstChild.style.backgroundColor=dojo.gfx.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);tdElem.firstChild.style.backgroundColor=bgColor;}else{tdElem.firstChild.style.backgroundColor=tdElem.firstChild.dBackgroundColor;}}}},/***Selectsanentirecolumn*@paramidxtheindexofthecolumntobeselected*@param_selectwhethertoselectordeselectthecolumn*/selectColumn:function(idx,_select){for(vari=0;i<this.spreadsheetHeight;i++){this.selectCell(idx,i,_select);}},/***Selectsanintervalofcolumns*@selectionEndColumnthelastcolumnoftheselection.Thefirstoneismaintainedatmouseevents*/selectColumns:function(selectionEndColumn){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.deselectAll();this.lastSelectedColumns=[];varminCol=selectionEndColumn<this.selectionStartColumn?selectionEndColumn:this.selectionStartColumn;varmaxCol=selectionEndColumn>this.selectionStartColumn?selectionEndColumn:this.selectionStartColumn;for(vari=minCol;i<=maxCol;i++){this.addColumnToSelection(i);this.selectColumn(i,true);}//selectfirstcelloffirstcolumnxthis.focusAt(this.selectionStartColumn,0);},/***Addsacolumntothelistofcolumnstobeselected*@paramidxtheindexofthecolumntobeselected*/addColumnToSelection:function(idx){this.lastSelectedColumns[this.lastSelectedColumns.length]=idx;},/***Selectsanentirerow*@paramidxtheindexoftherowtobeselected*@param_selectwhethertoselectordeselecttherow*/selectRow:function(idx,_select){for(vari=0;i<this.spreadsheetWidth;i++){this.selectCell(i,idx,_select);}},/***Selectsanintervalofrows*@selectionEndRowthelastrowoftheselection.Thefirstoneismaintainedatmouseevents*/selectRows:function(selectionEndRow){this.deselectAll();this.lastSelectedRows=[];varminRow=selectionEndRow<this.selectionStartRow?selectionEndRow:this.selectionStartRow;varmaxRow=selectionEndRow>this.selectionStartRow?selectionEndRow:this.selectionStartRow;for(vari=minRow;i<=maxRow;i++){this.addRowToSelection(i);this.selectRow(i,true);}//selectfirstcelloffirstrowthis.focusAt(1,this.selectionStartRow);},/***Addsarowtothelistofrowstobeselected*@paramidxtheindexoftherowtobeselected*/addRowToSelection:function(idx){this.lastSelectedRows[this.lastSelectedRows.length]=idx;},/***Returnstheselectionmode.Possiblevaluesare:SELECTION_MODES.RECTANGLEandSELECTION_MODES.RANDOM*RandommodewillbeusedwhenselectingrandomcellsusingSHIFT&CTRL.Notsupportedyet.*@returntheselectionmode*/getSelectionMode:function(){returnthis.selectionMode;},/***Returnsalistofselectedcells-tobeusedwhenselectionmodeisSELECTION_MODES.RANDOM*@returnalistofselectedcells*/getSelection:function(){varselectedCells=newArray();if(this.getSelectionMode()==this.SELECTION_MODES.RECTANGLE){if(this.lastSelectedRegion!=null){for(vari=this.lastSelectedRegion[0];i<=this.lastSelectedRegion[1];i++){for(varj=this.lastSelectedRegion[2];j<=this.lastSelectedRegion[3];j++){selectedCells[selectedCells.length]=[i,j];}}}else{selectedCells[selectedCells.length]=[this.currentFocusedCol,this.currentFocusedRow];}}returnselectedCells;},/***Returnstheselectionrectangle-tobeusedwhenselectionmodeisSELECTION_MODES.RECTANGLE*@returnanarraywith4coordinates:[colStart,colEnd,rowStart,rowEnd]*/getSelectionRectangle:function(){if(this.lastSelectedRegion&&this.lastSelectedRegion!=null){returnthis.lastSelectedRegion;}else{return[this.currentFocusedCol,this.currentFocusedCol,this.currentFocusedRow,this.currentFocusedRow];}},/***Deselectseverything*/deselectAll:function(){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.resetSelectedColumns();this.resetSelectedRows();if(this.lastSelectedRegion&&this.lastSelectedRegion!=null){this.selectRegion(this.lastSelectedRegion[0],this.lastSelectedRegion[1],this.lastSelectedRegion[2],this.lastSelectedRegion[3],false);}},/***Deselectsselectedcolumnsifany*/resetSelectedColumns:function(){for(vari=0;i<this.lastSelectedColumns.length;i++){this.selectColumn(this.lastSelectedColumns[i],false);}this.lastSelectedColumns=[];},/***Deselectsselectedrowsifany*/resetSelectedRows:function(){for(vari=0;i<this.lastSelectedRows.length;i++){this.selectRow(this.lastSelectedRows[i],false);}this.lastSelectedRows=[];},/***Resizesacolumn*@parametheDOMevent*@paramstorePositionwhethertostorepositionornot(usedwhenthemouseisstillmoving)*/resizeCol:function(e,storePosition){varpos=this.getCursorPosition(e);varnewX=pos.x;varcurrentCol=this.resizeOrigTH.dCellIndex+1;//if(currentResizedCol){vardelta=newX-this.resizeOrigXPos;varnewWidth=this.resizeOrigTH.dWidth+delta;if(newWidth<this.MINIMUM_CELL_WIDTH){newWidth=this.MINIMUM_CELL_WIDTH;}this.resizeOrigTH.style.width=this.toPx(newWidth);this.resizeOrigTH.firstChild.style.width=this.toPx(newWidth-3);this.resizeOrigTH.firstChild.firstChild.style.width=this.toPx(newWidth-5);for(vari=0;i<this.rows.length;i++){this.rows[i].cells[currentCol].firstChild.style.width=this.toPx(newWidth);}if(storePosition){this.resizeOrigTH.dWidth=newWidth;for(vari=0;i<this.rows.length;i++){this.rows[i].cells[currentCol].firstChild.dWidth=newWidth;}this._focus(this.currentFocusedCol,this.currentFocusedRow);}//}},/***Resizesarow*@parametheDOMevent*@paramstorePositionwhethertostorepositionornot(usedwhenthemouseisstillmoving)*/resizeRow:function(e,storePosition){varpos=this.getCursorPosition(e);varnewY=pos.y;varcurrentRow=this.getCellRow(this.resizeOrigTD);vardelta=newY-this.resizeOrigYPos;varnewHeight=this.rows[currentRow].dHeight+delta+2;if(newHeight<this.MINIMUM_CELL_HEIGHT){newHeight=this.MINIMUM_CELL_HEIGHT;}//resize1stcell(number+verticalresizer)this.rows[currentRow].cells[0].style.height=this.toPx(newHeight);this.rows[currentRow].cells[0].firstChild.firstChild.style.height=this.toPx(newHeight-(dojo.isIE?2:0));for(vari=1;i<this.rows[0].cells.length;i++){this.rows[currentRow].cells[i].firstChild.style.height=this.toPx(newHeight);}if(storePosition){this.rows[currentRow].dHeight=newHeight;for(vari=1;i<this.rows[0].cells.length;i++){this.rows[currentRow].cells[i].firstChild.dHeight=newHeight;}this._focus(this.currentFocusedCol,this.currentFocusedRow);}},/***Displaystheinputelementatagivenlocation*@param_tdElemthe<TD>elementoverwhichtheinputelementhastobedisplayed*/showInputOverTD:function(_tdElem){this.isEditing=true;//varpos=dojo.html.getAbsolutePosition(_tdElem,true);varpos=dojo.coords(_tdElem);with(this.inputElem){tdElem=_tdElem;//[D]style.width=dojo.html.getInnerWidth(_tdElem)+8;//style.width=dojo.html.getBorderBox(_tdElem).width+8;style.width=dojo.position(_tdElem).w+8;//[D]style.height=dojo.html.getInnerHeight(_tdElem)+8;style.height=dojo.position(_tdElem).h+8;style.left=pos.x-4;style.top=pos.y-4;style.zIndex=100;style.display="";if(tdElem!=null){if(typeof(tdElem.formula)=="undefined"){value="";}else{value=_tdElem.formula;}/*if(tdElem.cellType==this.CELL_TYPES.FORMULA){value=tdElem.formula;}else{value=tdElem.firstChild.innerHTML;}*/}else{value="";}oldValue=value;if(typeof(oldValue)=="undefined"||oldValue=="undefined"){oldValue="";}focus();}dijit.selectInputText(this.inputElem);},/***Hidestheinputelementandsavesthevalue*@paramisCancelwhethertocancelornotthemodificationstothecell*/hideInput:function(isCancel){this.isEditing=false;with(this.inputElem){//preventthisfromexecutingtwice-changethevalueandhidetheinputonlyifinputisvisibleif(style.display==""){if(tdElem!=null){if(isCancel){//tdElem.firstChild.innerHTML=oldValue;tdElem.formula=oldValue;}else{//tdElem.firstChild.innerHTML=value;tdElem.formula=value;}this.evalFormula(tdElem,true);}value="";style.display="none";}}},/***Deletesthecontentofthecurrentfocusedcell*/eraseCurrentCellContent:function(){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);tdElem.firstChild.innerHTML="";},/***Insertsanewcolumnbeforethecolumnofthecurrentfocusedcell*/insertColumnBefore:function(){try{varcolumnToInsertBefore=this.currentFocusedCol+1;varthead=this.domNode.getElementsByTagName("THEAD")[0];varths=thead.getElementsByTagName("TH");varnewTH=ths[columnToInsertBefore].cloneNode(true);//dojo.html.insertBefore(newTH,ths[columnToInsertBefore]);dojo.place(newTH,ths[columnToInsertBefore],"before");for(vari=0;i<this.rows.length;i++){varnewTD=this.rows[i].cells[columnToInsertBefore].cloneNode(true);//dojo.html.insertBefore(newTD,this.rows[i].cells[columnToInsertBefore]);dojo.place(newTD,this.rows[i].cells[columnToInsertBefore],"before");}this.resetSpreadsheet();//resetcell's formatting and contentif(columnToInsertBefore>=1){for(vari=0;i<this.rows.length;i++){this.rows[i].cells[columnToInsertBefore].firstChild.innerHTML="";this.unfocus(columnToInsertBefore,i);this.selectCell(columnToInsertBefore,i,false);}}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewcolumnafterthecolumnofthecurrentfocusedcell*/insertColumnAfter:function(){try{varthead=this.domNode.getElementsByTagName("THEAD")[0];varths=thead.getElementsByTagName("TH");varnewTH=ths[this.currentFocusedCol].cloneNode(true);//dojo.html.insertAfter(newTH,ths[this.currentFocusedCol]);dojo.place(newTH,ths[this.currentFocusedCol],"after");for(vari=0;i<this.rows.length;i++){varnewTD=this.rows[i].cells[this.currentFocusedCol].cloneNode(true);//dojo.html.insertAfter(newTD,this.rows[i].cells[this.currentFocusedCol]);dojo.place(newTD,this.rows[i].cells[this.currentFocusedCol],"after");}this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentif(this.currentFocusedCol>=1){for(vari=0;i<this.rows.length;i++){this.rows[i].cells[this.currentFocusedCol+1].firstChild.innerHTML="";this.unfocus(this.currentFocusedCol+1,i);this.selectCell(this.currentFocusedCol+1,i,false);}}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewrowbeforetherowofthecurrentfocusedcell*/insertRowBefore:function(){try{varnewTR=this.rows[this.currentFocusedRow].cloneNode(true);//dojo.html.insertBefore(newTR,this.rows[this.currentFocusedRow]);dojo.place(newTR,this.rows[this.currentFocusedRow],"before");this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentfor(vari=1;i<newTR.cells.length;i++){newTR.cells[i].firstChild.innerHTML="";this.unfocus(i,this.currentFocusedRow);this.selectCell(i,this.currentFocusedRow,false);}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewrowaftertherowofthecurrentfocusedcell*/insertRowAfter:function(){try{varnewTR=this.rows[this.currentFocusedRow].cloneNode(true);//dojo.html.insertAfter(newTR,this.rows[this.currentFocusedRow]);dojo.place(newTR,this.rows[this.currentFocusedRow],"after");this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentfor(vari=1;i<newTR.cells.length;i++){newTR.cells[i].firstChild.innerHTML="";this.unfocus(i,this.currentFocusedRow+1);this.selectCell(i,this.currentFocusedRow+1,false);}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Removeselectedrows*/removeRows:function(){varrowsToRemove=[];if(this.lastSelectedRows.length>0){for(vari=0;i<this.lastSelectedRows.length;i++){rowsToRemove[rowsToRemove.length]=this.lastSelectedRows[i];}}else{rowsToRemove[rowsToRemove.length]=this.currentFocusedRow;}varrowStr="";for(vari=0;i<rowsToRemove.length;i++){rowStr+="\t"+this.rows[rowsToRemove[i]].cells[0].firstChild.firstChild.innerHTML+"\n";}if(confirm("Are you sure you want to remove "+(rowsToRemove.length==1?"this row?\n":"these rows?\n")+rowStr)){try{for(vari=0;i<rowsToRemove.length;i++){dojo.doc.documentElement.removeNode(this.rows[rowsToRemove[i]]);}this.resetSpreadsheet();//focusontheclosestuppercellthis.focusAt(this.currentFocusedCol,this.currentFocusedRow);}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}}},/***Removeselectedcols*/removeCols:function(){varcolumnsToRemove=[];if(this.lastSelectedColumns.length>0){for(vari=0;i<this.lastSelectedColumns.length;i++){columnsToRemove[columnsToRemove.length]=this.lastSelectedColumns[i];}}else{columnsToRemove[columnsToRemove.length]=this.currentFocusedCol;}varths=this.domNode.getElementsByTagName("TH");varcolStr="";for(vari=0;i<columnsToRemove.length;i++){colStr+="\t"+ths[columnsToRemove[i]].firstChild.firstChild.innerHTML+"\n";}if(confirm("Are you sure you want to remove "+(columnsToRemove.length==1?"this column?\n":"these columns?\n")+colStr)){try{for(vari=0;i<columnsToRemove.length;i++){dojo.doc.documentElement.removeNode(ths[columnsToRemove[i]]);for(varj=0;j<this.rows.length;j++){dojo.doc.documentElement.removeNode(this.rows[j].cells[columnsToRemove[i]]);}}this.resetSpreadsheet();//focusontheclosestuppercellthis.focusAt(this.currentFocusedCol,this.currentFocusedRow);}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}}},/***Appliesoneoftheavailableformattingtypestothecell(FORMATTING_TYPES.FONT,FORMATTING_TYPES.FONT_SIZE,etc)*@paramstyleTypethestyletochange*@paramstyleValuethevalueforthestyle*/formatSelectedCells:function(styleType,styleValue){varsel=this.getSelection();//sel[i][0]givesthecolumn,sel[i][1]givestherowfor(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][0],sel[i][1]);this.addStyleToCell(styleType,styleValue,tdElem);this.applyStylesToCell(tdElem);}},/***Addsastyletothelistofstyles*@paramstyleTypethestyletochange*@paramstyleValuethevalueforthestyle*@paramtdElemthe<TD>elementtobeformatted*/addStyleToCell:function(styleType,styleValue,tdElem){if(typeof(tdElem.styleList)=="undefined"){tdElem.styleList=newArray();}//tdElem.styleList.add({style:styleType,value:styleValue});tdElem.styleList[styleType]=styleValue;},removeStyleForCell:function(style,tdElem){},/***Appliesthestylesforacell*@paramtdElemthe<TD>elementforwhichstylesareapplied*/applyStylesToCell:function(tdElem){varstyles=tdElem.styleList;if(typeof(styles)!="undefined"){//fontvarfont=styles[this.FORMATTING_TYPES.FONT];if(typeof(font)!="undefined"){tdElem.firstChild.style.fontFamily=font;}//fontsizevarfont_size=styles[this.FORMATTING_TYPES.FONT_SIZE];if(typeof(font_size)!="undefined"){tdElem.firstChild.style.fontSize=font_size;}//COLORvarcolor=styles[this.FORMATTING_TYPES.COLOR];if(typeof(color)!="undefined"){tdElem.firstChild.style.color=color;}//BG_COLORvarbgColor=styles[this.FORMATTING_TYPES.BG_COLOR];if(typeof(bgColor)!="undefined"){tdElem.firstChild.style.backgroundColor=bgColor;//varbgColor=dojo.html.getBackgroundColor(tdElem.firstChild);varbgColor=dojo.style(tdElem.firstChild,"backgroundColor");//[D]tdElem.firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//tdElem.firstChild.dBackgroundColor=dojo.gfx.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);tdElem.firstChild.dBackgroundColor=bgColor;}//BOLDvarbold=styles[this.FORMATTING_TYPES.BOLD];if(typeof(bold)!="undefined"){if(bold){tdElem.firstChild.style.fontWeight="bold";}else{tdElem.firstChild.style.fontWeight="";}}//ITALICvaritalic=styles[this.FORMATTING_TYPES.ITALIC];if(typeof(italic)!="undefined"){if(italic){tdElem.firstChild.style.fontStyle="italic";}else{tdElem.firstChild.style.fontStyle="";}}//UNDERLINEvarunderline=styles[this.FORMATTING_TYPES.UNDERLINE];if(typeof(underline)!="undefined"){if(underline){tdElem.firstChild.style.textDecoration="underline";}else{tdElem.firstChild.style.textDecoration="";}}}},/***Appliesaformula*@paramformulathenameoftheformula*/applyFormula:function(functionName){//minXandmaxYareusedtodeterminewheretheresultwillbewritten(inthebottom-leftcornerofthe//mostcomprehensiverectangle)varminCol=1000000;varmaxRow=-1;varsel=this.getSelection();//sel[i][0]givesthecolumn,sel[i][1]givestherowfor(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][1],sel[i][0]);minCol=minCol>sel[i][0]?sel[i][0]:minCol;maxRow=maxRow<sel[i][1]?sel[i][1]:maxRow;}//gettheleft-bottommostcellvarresultCell=this.getCell(minCol,maxRow+1);if(resultCell){if(this.getSelectionMode()==this.SELECTION_MODES.RECTANGLE){varcellColStart=this.fromArrToCellNotation(this.lastSelectedRegion[0],this.lastSelectedRegion[2]);varcellColStop=this.fromArrToCellNotation(this.lastSelectedRegion[1],this.lastSelectedRegion[3]);resultCell.formula="="+functionName+"("+cellColStart+":"+cellColStop+")";this.evalFormula(resultCell,true);}else{//onlyrectangleselectionmodeissupportedfornow,sowillNEVERgethereresultCell.formula="="+functionName+"(";for(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][1],sel[i][0]);varcellCol=String.fromCharCode("A".charCodeAt(0)+sel[i][0]-1);resultCell.formula=""+cellCol+(sel[i][1]+1)+(i==sel.length-1?"":",");}resultCell.formula=")";this.evalFormula(resultCell,true);}}},/***Checkstheentiregraphforcircularities*@throwsanexceptionifcircularitiesaredetected*/checkCircularities:function(){varstack=newArray();try{for(vari=0;i<this.ssGraph.length;i++){stack.push(i);this.checkCircularitiesPerNode(stack,i);stack.pop();}}catch(e){throw(e);}},/***Checksthegraphforcircularitiesgivenastartvertex*@throwsanexceptionifcircularitiesaredetected*/checkCircularitiesFromNode:function(node){varstack=newArray();try{stack.push(node);this.checkCircularitiesPerNode(stack,node);stack.pop();}catch(e){throw(e+" when evaluating cell "+this.fromGraphNodeToCellNotation(node));}},/***Recursivefunctionthatchecksforagivennodeifthereisacircularityinthegraph*@stackthestackofvisitednodes*@paramnodetheindexofthenodeinthematrix(0,1,2...mxn)wherem=numcolsandn=numrows*@throwsexceptionifcirculardependenciesaredetected*/checkCircularitiesPerNode:function(stack,node){for(vari=0;i<this.ssGraph.length;i++){//there's no need to avoid nodeX-nodeX relationships since they'reallgoingtobe0if(this.ssGraph[node][i]==1){//checkwhetherthestackalreadycontainsnodeifor(vark=0;k<stack.length;k++){if(stack[k]==i){throw"Circular Dependency Detected";//forcell:" + fromGraphNodeToCellNotation(i);}}stack.push(i);this.checkCircularitiesPerNode(stack,i);stack.pop();}}},/***Re-evaluatedependentcells.Thismethodalsochecksforcirculardependencies.*@throwsanexceptionifcircularitiesaredetected*/reevalDependentCells:function(node){varstack=newArray();try{stack.push(node);this.reevalDependentCellsPerNode(stack,node);stack.pop();}catch(e){throw(e+" when evaluating dependencies cell "+this.fromGraphNodeToCellNotation(node));}},/***Recursivefunctionfordetectingcellsdependentoncurrentcellandreevaluatingthem*@stackthestackofvisitednodes*@paramnodetheindexofthenodeinthematrix(0,1,2...mxn)wherem=numcolsandn=numrows*@throwsexceptionifcirculardependenciesaredetected*/reevalDependentCellsPerNode:function(stack,node){for(vari=0;i<this.ssGraph.length;i++){if(this.ssGraph[i][node]==1){for(vark=0;k<stack.length;k++){if(stack[k]==i){throw"Circular Dependency Detected";//forcell:" + fromGraphNodeToCellNotation(i);}}//re-evaluatecell's valuevarcell=this.getCellByCellNotation(this.fromGraphNodeToCellNotation(i));this.evalFormula(cell,true,true);stack.push(i);this.reevalDependentCellsPerNode(stack,i);stack.pop();}}},/***Returnsanarraycontaining(col,row)astheyareretrievedfromthecellnotation(A2,B33,etc).*Theindexesarerelativetothecellsspreadsheet(col0-isactuallythesecondcolumn-1stoneistheheader)*@paramcellNotationastringrepresentingthecellnotation*@returnanobjectwithtwoproperties:colandrow*/fromCellNotationToArr:function(cellNotation){varletter=""+cellNotation.match(/[a-zA-Z]*/);varnumber=""+cellNotation.match(/[0-9]+/);//buildtheindicesforthecellvarcol=this.fromCharToIdx(letter);varrow=parseInt(number)-1;return{"col":col,"row":row};},/***Createsacellnotation,givenacellandarow.Thecellandrowmuststartfrom0(thismeans,youcan't pass*rowIndexandcellIndexpropertiesof<TR>and<TD>elements.Youneedtohandleconversionfromtheseproperties*toproperindexes(usuallythisistransparentlyhandledbygetCellRowandgetCellCol).A(0,0)willbeA1incell*notation*@paramcolthecolumnindex(for0avalueof'A'willbereturned)*@paramrowtherowindex(for0avalueof1willbereturned)*@returnastringrepresentingthecellnotationA1,C5,etc*/fromArrToCellNotation:function(col,row){returnthis.fromIdxToChar(col)+(row+1);},/***Utilityfunctionfortransformingacharcodetoit's correspondent in number (a-0, b-1,...)*@paramchthechar*@returnanumber*/fromCharToIdx:function(ch){returnch.toLowerCase().charCodeAt(0)-"a".charCodeAt(0);},/***Utilityfunctionfortransformingandindextoitscorrespondingchar(0-a,1-b,...)*@idxtheindex*@returnanuppercasestringwithoneletter*/fromIdxToChar:function(idx){returnString.fromCharCode("a".charCodeAt(0)+idx).toUpperCase();},/***Returnsthecellnotationforanodeinthegraphofdependencies*@paramnodeIdxanumberrepresentingthenodeinthegraph*@returnastringrepresentingthecellnotationA1,C5,etc*/fromGraphNodeToCellNotation:function(nodeIdx){varrow=parseInt(nodeIdx/this.spreadsheetWidth);varcol=nodeIdx%this.spreadsheetWidth;returnthis.fromArrToCellNotation(col,row);},/***Returnsthenodeinthegraphofdependenciesforacolumn/row*@paramcolthecolumn*@paramrowtherow*@returnanumberrepresentingthenodeinthegraphofdependencies*/fromCellToGraphNode:function(col,row){returncol+row*this.spreadsheetWidth;},/***Retrievesthe<TD>elementbasedonthecellnotation(A1,C5,etc)*@paramcellStrastringrepresentingthecellnotation*@returnthe<TD>object*/getCellByCellNotation:function(cellStr){varcellCoords=this.fromCellNotationToArr(cellStr);returnthis.getCell(cellCoords.col,cellCoords.row);},/***Returnstherowforacellinthespreadsheetgivena<TD>element.NoteIEkeepstrackofTHelementsalso.*(ignoringcellheaders)*@paramtdElemthe<TD>element*@returntherowindex*/getCellRow:function(tdElem){returntdElem.parentNode.rowIndex-1;},/***Returnsthecolumn(withinthespreadsheet)foracellinthespreadsheetfora<TD>element(ignoringcellheaders)*@paramtdElemthe<TD>element*@returnthecolumnindex*/getCellCol:function(tdElem){returntdElem.cellIndex-1;},/***Returnsthe<TD>elementforagivencellinthespreadsheet.Forexample,getCell(0,0)shouldreturnthefirstcell*onthefirstrow(ignoringfirstcolumnandthethead).*@paramcolanumberrepresentingthecolofthecellinthespreadsheet.Startsfrom0(0beingtheequivalentofcolumnA).*@paramrowanumberrepresentingtherowofthecellinthespreadsheet.Startsfrom0(0beingtheequivalentofrow1).*@returna<TD>object*/getCell:function(col,row){if(dojo.isIE){returnthis.rows[row].cells[col+1];}else{returnthis.rows[row].cells[col+1];}},/***Utilityfunctionfordebuggingthegraphformanuallycheckingthedependencies*@returnastringwiththeentiregraph*/debugGraph:function(){varstr=" ";for(vari=0;i<this.ssGraph[0].length;i++){str+=this.fromGraphNodeToCellNotation(i)+" ";}str+="\n";for(varr=0;r<this.ssGraph.length;r++){str+=this.fromGraphNodeToCellNotation(r)+": [";for(varc=0;c<this.ssGraph[r].length;c++){str+=" "+this.ssGraph[r][c]+",";}str+="]\n"}returnstr;},/***Returnsthenumberofquotationmarksignoringtheescapedone*@paramstrthestringtoolookforquotationinside*@paramstartanintegerrepresentingthepositiontostartlookingfor*@paramstopanintegerrepresentingthepositiontostoplookingfor*/getNumberOfQuotes:function(str,start,stop){varnumQuotes=0;for(vari=start;i<stop;i++){if(str.charAt(i)=='"'){if(numQuotes%2==1&&i>0&&str.charAt(i-1)=="\\"){if(i>1&&str.charAt(i-2)=="\\"){numQuotes++;}}else{numQuotes++;}}}returnnumQuotes;},/***Evaluatesaformulaforacell,andputstheresultbackinthecell*@cellthespreadsheetcellwhichhasamongstotherpropertiesaformulapropertywhichisa*Stringcontainingtheformula.Examplesofstringsare:*sum(e4:b6),sum(e2,b4,c5)+cos(3.14)*avg(1,2,3),etc*@evaluateiftrue,thecell's value will be evaluated again. If false, if the cell'stypehas*beendetectedanditsformulahasbeenanalyzed,returndirectlythevalue*@noDependenciesiftrue,dependenciesarenotre-evaluated*@returntheresultoftheformula*/evalFormula:function(_cell,evaluate,noDependencies){varcellNotation=this.fromArrToCellNotation(this.getCellCol(_cell),this.getCellRow(_cell));varformula=_cell.formula;varerrors=false;if(formula==""||typeof(formula)=="undefined"){return"";}//acell's value it'saformulaonlyifitstartswith"="if(!evaluate&&_cell.cellType!=this.CELL_TYPES.FORMULA){return_cell.formula;}varresult;varoriginalGraphNode=this.fromCellToGraphNode(this.getCellCol(_cell),this.getCellRow(_cell));if(trim(""+formula).charAt(0)!="="){//trytodetectatypeforthecell(date,string,number)vartmp=formula.toLowerCase();//checkifit's a datevar_val;if((_val=this.parseDateFormat1(tmp))!=null){_cell.cellType=this.CELL_TYPES.DATE;}elseif((_val=this.parseDateFormat2(tmp))!=null){_cell.cellType=this.CELL_TYPES.DATE;}elseif((_val=this.parseNumberFormat1(tmp))!=null){//checkifit's a number_cell.cellType=this.CELL_TYPES.NUMBER;}else{//ifnoneoftheabove,consideritastring_val=formula;_cell.cellType=this.CELL_TYPES.STRING;}_cell.formula=_val;result=_val;}else{_cell.cellType=this.CELL_TYPES.FORMULA;this.debug("STEP 1: transform intervals of cells for "+cellNotation+": "+_cell.formula);/********************************************************************STEP1:transformintervalsofcellstoarrayofcells(B2:C3=>B2,B3,C2,C3*********************************************************************/varpcs=formula.match(this.reInterval);varinlinedFormula=formula;if(pcs!=null){//foreachinterval//TODOcheckthecellsisnotpartofastringfor(vari=0;i<pcs.length;i++){varcells=pcs[i].split(":");varcell0=this.fromCellNotationToArr(cells[0]);varcell1=this.fromCellNotationToArr(cells[1]);//buildastringwithalltheintermediaryvaluesvarinlinedInterval="";for(varcolIdx=cell0.col;colIdx<=cell1.col;colIdx++){for(varrowIdx=cell0.row;rowIdx<=cell1.row;rowIdx++){inlinedInterval+=this.fromIdxToChar(colIdx)+(rowIdx+1)+",";}}//removethelastcommainlinedInterval=inlinedInterval.substring(0,inlinedInterval.length-1);//replacedintervalwithinlineformula//foreachoccofcells,replaceitwithinlinedIntervalvarcellsPos=0;while((cellsPos=inlinedFormula.indexOf(pcs[i],cellsPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellsPos);if(numQuotes%2==0){inlinedFormula=inlinedFormula.substring(0,cellsPos)+inlinedInterval+inlinedFormula.substring(cellsPos+pcs[i].length);}cellsPos+=pcs[i].length;}}}this.debug("STEP 2: search for cell notations and mark the graph for "+cellNotation+": "+inlinedFormula);/********************************************************************STEP2:searchforcellnotationsthatarenotinsidestringsandmarkthegraph*********************************************************************///resetthegraphdependenciesforthiscellfor(vargrIdx=0;grIdx<this.spreadsheetWidth*this.spreadsheetHeight;grIdx++){this.ssGraph[originalGraphNode][grIdx]=0;}varcellsMatches=inlinedFormula.match(this.reCell);if(cellsMatches!=null){//foreachcellfor(vari=0;i<cellsMatches.length;i++){varcell=cellsMatches[i].substring(1);//markedgesingraphonlyforcellsthatarenotinsidestringsvarcellPos=0;while((cellPos=inlinedFormula.indexOf(cell,cellPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellPos);if(numQuotes%2==0){//marktheedgesinthegraphvarcellCoords=this.fromCellNotationToArr(cell);vargraphNode=this.fromCellToGraphNode(cellCoords.col,cellCoords.row);//alert("dependency : "+cellNotation+" "+this.fromArrToCellNotation(cellCoords.col,cellCoords.row));this.ssGraph[originalGraphNode][graphNode]=1;}cellPos+=cell.length;}}}try{this.debug("STEP 3: check circularities for "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP3:checkcircularities*********************************************************************/this.checkCircularitiesFromNode(originalGraphNode);this.debug("STEP 4: evaluate each cell's value for "+cellNotation);/********************************************************************STEP4:ifnocircularities,replaceeachcellnamewithitsvalue*********************************************************************/varcells=inlinedFormula.match(this.reCell);if(cells!=null){//foreachcell//TODOcheckthecellsisnotpartofastringfor(vari=0;i<cells.length;i++){varcell=cells[i].substring(1);//replacedcellwithit.lengtsvaluevarcellPos=0;while((cellPos=inlinedFormula.indexOf(cell,cellPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellPos);if(numQuotes%2==0){varcellValue;varcellObj=this.getCellByCellNotation(cell);try{cellValue=this.evalFormula(cellObj,false,true);}catch(e){throwe;}//forstrings,thevaluetoreplacehastocontainthequotesvartoReplace="";if(cellObj.cellType==this.CELL_TYPES.NUMBER){toReplace=cellValue;}if(cellObj.cellType==this.CELL_TYPES.STRING){toReplace="\""+cellValue+"\"";}if(cellObj.cellType==this.CELL_TYPES.FORMULA){toReplace=cellValue;}//ifcellhasnovalue,removeprevious,ifexistsorifpreviouscharis(removenext,//makesurethecellthathavenovaluedon't affect the formula by leaving random commasif(toReplace==""){vartmp=trim(inlinedFormula.substring(0,cellPos));vartmp2=trim(inlinedFormula.substring(cellPos+cell.length));//twocases:commaisbeforeandafterif(cellPos>0&&tmp.charAt(tmp.length-1)==','){inlinedFormula=inlinedFormula.substring(0,cellPos-1)+toReplace+inlinedFormula.substring(cellPos+cell.length);}else{if(cellPos>0&&tmp.charAt(tmp.length-1)=='('&&cellPos<inlinedFormula.length-1&&tmp2.charAt(0)==','){inlinedFormula=tmp+toReplace+tmp2.substring(1);}}}else{inlinedFormula=inlinedFormula.substring(0,cellPos)+toReplace+inlinedFormula.substring(cellPos+cell.length);}}cellPos+=cell.length;}}}this.debug("STEP 5: turn functions to lower case for "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP5:turnfunctiontolowercase*********************************************************************/varfunctions=inlinedFormula.match(this.reFunction);if(functions!=null){//foreachfnfor(vari=0;i<functions.length;i++){varfnToLower=functions[i].toLowerCase();//onlyifit's not lower alreadyif(fnToLower!=functions[i]){varfnPos=0;while((fnPos=inlinedFormula.indexOf(functions[i],fnPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,fnPos);if(numQuotes%2==0){inlinedFormula=inlinedFormula.substring(0,fnPos)+fnToLower+inlinedFormula.substring(fnPos+functions[i].length);}fnPos+=functions[i].length;}}}}//andnowevaluatetheformularesult=eval(inlinedFormula.substring(1));this.debug("result formula for "+cellNotation+", formula: "+inlinedFormula);}catch(e){this.debug(e);//throw(e);result=e;errors=true;}}if(!errors){if(!noDependencies){this.debug("STEP 6: re-evaluate cells dependent on this very cell: "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP6:reevaluatedependentcells*********************************************************************/this.reevalDependentCells(originalGraphNode);}else{this.debug("STEP 6: dependencies will NOT be re-evaluated for cell: "+cellNotation);}}_cell.firstChild.innerHTML=result;this.debug("Final result for "+cellNotation+": "+result);returnresult;//returnthis.formatCellForPresentation(cell);;},/***Firesanevent*@paramevttheeventtobefired*/_fireEvent:function(evt){if(typeofthis[evt]=="function"){varargs=[this];for(vari=1;i<arguments.length;i++){args.push(arguments[i]);}this[evt].apply(this,args);}},/***Formatsthecellforpresentation.Theformattingshouldbebasedoncell's type (number, date, string) and cell's*format.Possibleformatsfordateare"MM/DD/YYYY","DD-MMM-YYYY",etc.*Currentlycell's formats are not supported yet.*@paramcellthe<TD>elementtobeformattedforpresentation*@returntheformattedvalue*/formatCellForPresentation:function(cell){varformula=cell.formula;if(formula&&typeof(formula)!="undefined"&&formula!=null){//now,thecellformatshouldbechecked...if(formulainstanceofDate){with(formula){returngetDate()+"-"+this.months[getMonth()].toUpperCase()+"-"+getFullYear();}}//now,thecellformatshouldbechecked...if(typeof(formula)=="number"){returnformula;}}},/***Createsadatefromastringparsingformat1:MM/DD/YYYY*@paramstrthestringtobeparsed*@returnaDateobjectifparsingsucceededornullifstringcouldnotbeparsed*/parseDateFormat1:function(str){var_date=str.match(this.reDate1);if(_date&&_date!=null){_date=""+_date;if(_date==trim(str)){varvals=_date.split("/");varmonth=parseInt(vals[0]);varday=parseInt(vals[1]);varyear=parseInt(vals[2]);if(this.isDateValid(day,month,year)){if(year<100&&year>=30){year=2000+year;}elseif(year<100){year=1900+year;}vardateObj=newDate();dateObj.setFullYear(year);dateObj.setMonth(month-1);dateObj.setUTCDate(day);returndateObj;}}}returnnull;},/***Createsadatefromastringparsingformat2:DD-MMM-YYYY*@paramstrthestringtobeparsed*@returnaDateobjectifparsingsucceededornullifstringcouldnotbeparsed*/parseDateFormat2:function(str){var_date=str.match(this.reDate2);if(_date&&_date!=null){_date=""+_date;if(_date==trim(str)){varvals=_date.split("-");varmonth=vals[1];varfound=-1;for(vari=0;i<this.months.length;i++){if(this.months[i]==month){found=i;break;}}if(found==-1){returnnull;}varday=parseInt(vals[0]);varyear=parseInt(vals[2]);if(this.isDateValid(day,month,year)){if(year<100&&year>=30){year=2000+year;}elseif(year<100){year=1900+year;}vardateObj=newDate();dateObj.setFullYear(year);dateObj.setMonth(found);dateObj.setUTCDate(day);returndateObj;}}}returnnull;},/***Createsanumberfromastring*@paramstrthestringtobeparsed*@returnanintorafloatifparsingsucceededornullifstringcouldnotbeparsed*/parseNumberFormat1:function(str){var_num=str.match(this.reNumber1);if(_num&&_num!=null){returnnull;}vardotIdx=str.indexOf(".");if(dotIdx!=-1&&dotIdx!=str.lastIndexOf(".")){returnnull;}vareIdx=str.indexOf("e");if(eIdx!=-1&&eIdx!=str.lastIndexOf("e")){returnnull;}if(dotIdx!=-1&&eIdx!=-1&&dotIdx+1!=eIdx){returnnull;}var_int=parseInt(str);if(""+_int==str){return_int;}var_float=parseFloat(str);if(!isNaN(_float)){return_float;}returnnull;},/***Validatesadate.Notimplementedyet-justasimplechecktherangesforeachparamaregood*@paramday*@parammonth*@paramyear*/isDateValid:function(day,month,year){if(month<1&&month>12&&day<1&&day>31){returnfalse;}//TODOcheckvaliddatereturntrue;},/***Spreadsheetspecificdebugfunction*@parammsgastringrepresentingthemessagetodebug*/debug:function(msg){vardate=newDate();vartmp=date.getHours()+":"+date.getMinutes()+"-"+date.getSeconds()+":"+date.getMilliseconds()+" : "+msg;vardbg=document.getElementById("debugDiv");dbg.value=tmp+"\n"+dbg.value;console.debug(tmp);},/***Adds"px"toanumber*@paramnumthenumber*/toPx:function(num){returnnum+"px";}}
);
/**************
MATHEMATICAL FUNCTIONS ***************/
function sum() {
var _sum = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_sum += arguments[i];
}
}
return _sum;
}
function avg() {
var _avg = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_avg += arguments[i];
}
_avg /= arguments.length;
}
return _avg;
}
function min() {
var _min = Number.POSITIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_min > arguments[i]) {
_min = arguments[i];
}
}
}
return _min;
}
function max() {
var _max = Number.NEGATIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_max < arguments[i]) {
_max = arguments[i];
}
}
}
return _max;
}
function product() {
var _product = 1;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_product *= arguments[i];
}
}
return _product;
}
var abs = Math.abs;
var acos = Math.acos;
var asin = Math.asin;
var atan = Math.atan;
var atan2 = Math.atan2;
var ceil = Math.ceil;
var cos = Math.cos;
var exp = Math.exp;
var floor = Math.floor;
var log = Math.log;
var pow = Math.pow;
var random = Math.random;
var round = Math.round;
var sin = Math.sin;
var sqrt = Math.sqrt;
var tan = Math.tan;
/**************
TEXT FUNCTIONS ***************/
function len() {
if(arguments != null && arguments.length > 0) {
return arguments[0].length;
}
}
Copyright (c) 2005-2006 Tremend Software Consulting, Licensed under the Academic Free License version 2.1 or BSD licenses
*/
dojo.provide("dojox.widget.iSpread");
dojo.provide("dojox.widget.iSpreadSheet");
/** * Create toolbar, tabcontainer and first sheet */postCreate:function(args,frag){this.createToolbar();this.createTabContainer();this.createSheet("sheet 1");},button:function(iconClass){returnnewdijit.form.Button({label:"button",showLabel:false,iconClass:iconClass});},/** * Initializes the toolbar */createToolbar:function(){tb=newdijit.Toolbar();this.domNode.appendChild(tb.domNode);tb.addChild(this.button(this.img("justifyleft")));tb.addChild(this.button(this.img("justifycenter")));tb.addChild(this.button(this.img("justifyright")));tb.addChild(this.button(this.img("justifyfull")));this.fontMenu=newdijit.form.Select({name:"formatBlock",options:[ {label: "Font", value: "-1"}, {label: "Serif", value: "serif"}, {label: "Sans-serif", value: "sans-serif"}, {label: "Cursive", value: "cursive"}, {label: "Fantasy", value: "fantasy"}, {label: "Monospace", value: "monospace"}]});dojo.connect(this.fontMenu,"onChange",this,"changeFont");//this.fontMenu.domNode.getElementsByTagName("select")[0].style.width="80px";tb.addChild(this.fontMenu);//fontsizemenuthis.fontSizeMenu=newdijit.form.Select({name:"formatBlock",options:[ {label: "Size", value: "-1"}, {label: "10", value : "10"}, {label: "12", value : "12"}, {label: "14", value : "14"}, {label: "16", value : "16"}, {label: "18", value : "18"}, {label: "24", value : "24"}, {label: "32", value : "32"}, {label: "40", value : "40"}]});dojo.connect(this.fontSizeMenu,"onChange",this,"changeFontSize");//this.fontSizeMenu.domNode.style.width="55px";tb.addChild(this.fontSizeMenu);//separatortb.addChild(newdijit.ToolbarSeparator());//boldtogglebuttonthis.boldItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("bold")});dojo.connect(this.boldItem,"onClick",this,"makeBold");tb.addChild(this.boldItem);//italictogglebuttonthis.italicItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("italic")});dojo.connect(this.italicItem,"onClick",this,"makeItalic");tb.addChild(this.italicItem);//underlinetogglebuttonthis.underlineItem=newdijit.form.ToggleButton({showlabel:false,iconClass:this.img("underline")});dojo.connect(this.underlineItem,"onClick",this,"makeUnderline");tb.addChild(this.underlineItem);//separatortb.addChild(newdijit.ToolbarSeparator());//colordialogthis.colorItem=newdijit.form.DropDownButton({iconClass:this.img("forecolor")});this.colorItem.colorPalette=newdijit.ColorPalette({palette:"3x4",style:"display: none"});this.colorItem.addChild(this.colorItem.colorPalette);dojo.connect(this.colorItem.colorPalette,"onChange",this,"changeColor");tb.addChild(this.colorItem);//bgcolordialogthis.bgcolorItem=newdijit.form.DropDownButton({iconClass:this.img("backcolor")});this.bgcolorItem.bgcolorPalette=newdijit.ColorPalette({palette:"3x4",style:"display: none"});this.bgcolorItem.addChild(this.bgcolorItem.bgcolorPalette);dojo.connect(this.bgcolorItem.bgcolorPalette,"onChange",this,"changeColor");tb.addChild(this.bgcolorItem);//sheetmenuthis.sheetMenu=newdijit.form.Select({name:"sheetMenu",options:[ {label: "Sheet", value : "-1"}, {label: "Rename", value : "1"}, {label: "Delete", value : "2"}, {label: "New", value : "3"}]});dojo.connect(this.sheetMenu,"onChange",this,"sheetAction");//this.sheetMenu.domNode.style.width="65px";tb.addChild(this.sheetMenu);//functionsmenuthis.functionsMenu=newdijit.form.Select({name:"functionsMenu",options:[ {label: "Functions", value : "-1"}, {label: "Sum", value: "sum"}, {label: "Product", value : "product"}, {label: "Average", value : "avg"}, {label: "Min", value : "min"}, {label: "Max", value : "max"}, {label: "Count", value: "count"}]});dojo.connect(this.functionsMenu,"onChange",this,"applyFunction");//this.functionsMenu.domNode.style.width="85px";tb.addChild(this.functionsMenu);},/** * Util function. The same as the one in test_toolbar.html. Returns the image from src/widget/spreadsheet/templates/buttons * @param name the name of image (no extension) */img:function(name){returnthis.iconMap[name]+" toolbarButton";},/** * Creates the tab container which will hold the sheets */createTabContainer:function(){debugger;this.tabContainer=newdijit.layout.TabContainer({style:"height: 100%; width: 100%;",tabPosition:"bottom"});this.domNode.appendChild(this.tabContainer.domNode);dojo.connect(this.tabContainer,"selectChild",this,"tabChanged");this.tabContainer.startup();},/** * Callback for row menu * @param item the menu item * @param val the value for the item selected */rowAction:function(item,val){if(val!="-1"){switch(val){case"1"://insertrowbeforethis.tabs[this.activeTab].sheet.insertRowBefore();break;case"2"://insertrowbeforethis.tabs[this.activeTab].sheet.insertRowAfter();break;case"3"://insertrowbeforethis.tabs[this.activeTab].sheet.removeRows();break;}this.setSelectIndex(this.rowsMenu,0);}},/** * Callback for column menu * @param item the menu item * @param val the value for the item selected */colAction:function(item,val){if(val!="-1"){switch(val){case"1"://insertrowbeforethis.tabs[this.activeTab].sheet.insertColumnBefore();break;case"2"://insertrowbeforethis.tabs[this.activeTab].sheet.insertColumnAfter();break;case"3"://insertrowbeforethis.tabs[this.activeTab].sheet.removeCols();break;}this.setSelectIndex(this.rowsMenu,0);}},/** * Callback for sheet menu * @param item the menu item * @param val the value for the item selected */sheetAction:function(item,val){if(val!="-1"){switch(val){case"1"://renamecurrentsheetvarnewVal=prompt("Enter the new name for the sheet");if(newVal){this.tabs[this.activeTab].div.getElementsByTagName("span")[0].innerHTML=newVal;this.tabs[this.activeTab].label=newVal;}break;case"2"://deletecurrentsheetthis.removeCurrentSheet();break;case"3"://newsheetthis.createSheet("sheet "+(this.tabs.length+1));break;}this.setSelectIndex(this.sheetMenu,0);}},setSelectIndex:function(select,index){varoptions=select.getOptions();if(options&&options.length&&options[index])select.attr("value",options[index].value);},/** * Applies a formula * @param item the menu item * @param val the value for the item selected */applyFunction:function(item,val){if(this.functionsMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.applyFormula(this.functionsMenu.attr("value"));}},/** * Callback for font size menu */changeFontSize:function(e){if(this.fontSizeMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.FONT_SIZE,this.fontSizeMenu.attr("value"));this.setSelectIndex(this.fontSizeMenu,0);}},/** * Callback for font size menu */changeFont:function(e){if(this.fontMenu.attr("value")!="-1"){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.FONT,this.fontMenu.attr("value"));this.setSelectIndex(this.fontMenu,0);}},/** * Callback for color picker */changeColor:function(color){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.COLOR,this.colorItem.colorPalette.attr("value"));},/** * Callback for background color picker */changeBGColor:function(e){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.BG_COLOR,this.bgcolorItem.bgcolorPalette.attr("value"));},/** * Callback for bold button */makeBold:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.BOLD,this.boldItem.attr("checked"));},/** * Callback for italic button */makeItalic:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.ITALIC,this.italicItem.attr("checked"));},/** * Callback for underline button */makeUnderline:function(){this.tabs[this.activeTab].sheet.formatSelectedCells(dojox.widget.iSpreadSheet.prototype.FORMATTING_TYPES.UNDERLINE,this.underlineItem.attr("checked"));},/** * Creates a new sheet (new ContentPane and a new sheet inside) * @param name the name of the sheet */createSheet:function(sheetName){//createthecontentpaneforthenewtabforthisnewsheetvarcurrentTabIdx=this.tabs.length;this.tabs[currentTabIdx]=newdijit.layout.ContentPane({id:"sheet"+currentTabIdx,title:sheetName});this.tabContainer.addChild(this.tabs[currentTabIdx]);//calledonce(otherwisetheselectiongetsbrokenthis.tabContainer.selectChild(this.tabs[currentTabIdx]);varv=newdojox.widget.iSpreadSheet();v.init(this.tabs[currentTabIdx]);this.tabs[currentTabIdx].sheet=v;this.activeTab=currentTabIdx;//secondcallisnecessary,sincesomepropsaresetbeforethiscallthis.tabContainer.selectChild(this.tabs[currentTabIdx]);//toolbartogglebuttonsneedtobenotifiedsothattheyreflectthestate//ofthecell(ifcellhasboldstyle,boldbuttonmustbetoggled)dojo.connect(v,"setFormatting",this,"setFormatting");},/** * Event handler for "setFormatting" event thrown by the sheet object. This is useful for chaning button states * according to cell's formatting. If one cell has bold style, the toolbar should reflect this state * * @param spreadsheet the sheet that triggered the event * @param _bold true if bold enabled, false otherwise * @param _italic true if italic enabled, false otherwise * @param _underline true if underline enabled, false otherwise */setFormatting:function(spreadsheet,_bold,_italic,_underline){//this.boldItem.setSelected(_bold);this.boldItem.attr("checked",_bold);//this.italicItem.setSelected(_italic);this.italicItem.attr("checked",_italic);//this.underlineItem.setSelected(_underline);this.underlineItem.attr("checked",_underline);},/** * Removes the current working sheet */removeCurrentSheet:function(){if(this.tabs.length>1){this.tabContainer.removeChild(this.tabs[this.activeTab]);for(vari=this.activeTab;i<this.tabs.length-1;i++){this.tabs[i]=this.tabs[i+1];}this.tabs.length--;this.activeTab=this.activeTab>0?this.activeTab-1:this.activeTab;}else{alert("The document must have at least one sheet");}},/** * Handles sheet change. This is needed for the sheet to decouple certain events that may mess up how sheet receive events */tabChanged:function(){for(vari=0;i<this.tabs.length;i++){if(this.tabs[i]==this.tabContainer.selectedTabWidget){this.activeTab=i;if(this.tabs[i].sheet){this.tabs[i].sheet.gainFocus();}}else{if(this.tabs[i].sheet){this.tabs[i].sheet.loseFocus();}}}}}
/***Regularexpressionsfordetectingcellintervals,cellsorfunctions*/reInterval:/[a-zA-Z]{1}[0-9]+:[a-zA-Z]{1}[0-9]+/g,reCell:/[^a-zA-Z]{1}[a-zA-Z]{1}[0-9]+/g,reFunction:/[a-zA-Z]{3,}[a-zA-Z0-9]*\(/g,/***Fordetectingcirculardependencies,thespreadsheetwillberepresentedasa*directedgraph*Thegraphisrepresentedasamatrixinwhichavalueof1meansthere's a direct dependency*betweennodeAandnodeB.Forexample,ifA->B,A->C,B->D,B->E,D->C,C->B,thegraphwilllooklike:*ABCDE*__________*A|01100*B|00011*C|01000*D|00100*E|00000*/ssGraph:null,/***Thisobjectwillholdamapwithcorrespondencesbtwcellnotationandnumberinmatrix*(A1-0,A2-1,A3-2...,B15-20)*/cellGraphLookup:null,domNode:null,/****/months:["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],reDate1:/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,4}/,reDate2:/[0-9]{1,2}-[a-z]{3}-[0-9]{4}/,reNumber1:/[^0-9e\.]/,getCursorPosition:function(e){e=e||window.event;varcursor={x:0,y:0};if(e.pageX||e.pageY){cursor.x=e.pageX;cursor.y=e.pageY;}else{varde=dojo.doc.documentElement;vardb=dojo.body;cursor.x=e.clientX+((de||db)["scrollLeft"])-((de||db)["clientLeft"]);cursor.y=e.clientY+((de||db)["scrollTop"])-((de||db)["clientTop"]);}returncursor;},postCreate:function(){},/***Initializesthegraphicwidget(table,column/rowheaders,etc)*@paramcontentPanetheContentPaneobjectcorrespondingtoatabinaTabContainer*/init:function(contentPane){debugger;this.domNode=contentPane.domNode;//createthetableforthissheetthis.createSpreadsheetCells(contentPane);this.resetSpreadsheet();this.initGraph();//disableselection//dojo.html.disableSelection(this.domNode);dojo.setSelectable(this.domNode,false);this.gainFocus();this.createInputElem();this._focus(this.currentFocusedCol,this.currentFocusedRow);//browserdetectionthis.isIE=/msie/i.test(navigator.userAgent);this.isChrome=/chrome/i.test(navigator.userAgent);},/***Calledwhenasheetislosingfocus(othersheetbecomesactive)-disconnectseventhandlers*/loseFocus:function(){//dojo.event.disconnect(this.domNode,"onmousedown",this,"onMouseDown");dojo.disconnect(this.domNode,"onmousedown",this,"onMouseDown");//dojo.event.disconnect(this.domNode,"onmousemove",this,"onMouseMove");dojo.disconnect(this.domNode,"onmousemove",this,"onMouseMove");//dojo.event.disconnect(this.domNode,"onmouseup",this,"onMouseUp");dojo.disconnect(this.domNode,"onmouseup",this,"onMouseUp");//dojo.event.disconnect(this.domNode,"onmouseover",this,"onMouseOver");dojo.disconnect(this.domNode,"onmouseover",this,"onMouseOver");//dojo.event.disconnect(document,"onkeypress",this,"onKeyPress");dojo.disconnect(document,"onkeypress",this,"onKeyPress");//dojo.event.disconnect(document,"onkeyup",this,"onKeyUp");dojo.disconnect(document,"onkeyup",this,"onKeyUp");//dojo.event.disconnect(this.domNode,"ondblclick",this,"onDblClick");dojo.disconnect(this.domNode,"ondblclick",this,"onDblClick");},/***Calledwhenasheetisgainingfocus-reconnectseventhandlers*/gainFocus:function(){//makesureeventsarenotconnectedtwicethis.loseFocus();//dojo.event.connect(this.domNode,"onmousedown",this,"onMouseDown");dojo.connect(this.domNode,"onmousedown",this,"onMouseDown");//dojo.event.connect(this.domNode,"onmousemove",this,"onMouseMove");dojo.connect(this.domNode,"onmousemove",this,"onMouseMove");//dojo.event.connect(this.domNode,"onmouseup",this,"onMouseUp");dojo.connect(this.domNode,"onmouseup",this,"onMouseUp");//dojo.event.connect(this.domNode,"onmouseover",this,"onMouseOver");dojo.connect(this.domNode,"onmouseover",this,"onMouseOver");//dojo.event.connect(document,"onkeypress",this,"onKeyPress");dojo.connect(document,"onkeypress",this,"onKeyPress");//dojo.event.connect(document,"onkeyup",this,"onKeyUp");dojo.connect(document,"onkeyup",this,"onKeyUp");//dojo.event.connect(this.domNode,"ondblclick",this,"onDblClick");dojo.connect(this.domNode,"ondblclick",this,"onDblClick");},/***Createsthespreadsheetcells(theactual<TABLE>element)*@paramcontentPanetheContentPaneobjectassociatedwithaTabContainer*/createSpreadsheetCells:function(contentPane){varhtml='';html+='<div style="height:100%;width:100%;overflow:auto;">';html+='<table class="sheet" cellspacing="0" cellpadding="0" >';html+=' <thead>';html+=' <th class="sheetRow1stCell"></th>';for(varcol=0;col<10;col++){html+=' <th><div class="header"><div class="headerText">A</div><div class="horizontalResizer"> </div></div></th>';}html+=' </thead>';html+=' <tbody>';for(varrow=0;row<20;row++){html+=' <tr>';html+=' <td class="sheetRow1stCell"><div><div class="rowHeaderText"></div><div class="verticalResizer"> </div></div></td>';for(varcol=0;col<10;col++){html+=' <td class="sheetCell"><div class="sheetCellContent"></div></td>';}html+=' </tr>';}html+=' </tbody>';html+='</table>';html+='</div>';contentPane.attr("content",html);},/***Initializesthedependenciesgraph*/initGraph:function(){this.spreadsheetWidth=this.rows[0].cells.length-1;this.spreadsheetHeight=dojo.isIE?(this.rows.length-1):this.rows.length;this.ssGraph=newArray();//initializethegraphedgesvarnumNodes=this.spreadsheetWidth*this.spreadsheetHeight;for(vari=0;i<numNodes;i++){this.ssGraph[i]=newArray();for(varj=0;j<numNodes;j++){this.ssGraph[i][j]=0;}}//populatethelookupthis.cellGraphLookup=newObject();for(vari=0;i<this.spreadsheetWidth;i++){for(varj=1;j<=this.spreadsheetHeight;j++){this.cellGraphLookup[String.fromCharCode("A".charCodeAt(0)+i)+j]=j*this.spreadsheetWidth+i;}}},/***Applieslabelstocolumn/rowheaders.Fixeswidthoffirstcolumnandinitializesinternaldataforeachcell/header*/resetSpreadsheet:function(){this.tbody=this.domNode.getElementsByTagName("tbody")[0];this.rows=this.tbody.getElementsByTagName("tr");for(vari=0;i<this.rows.length;i++){//-notdiscoveredyet-forsomereasonsFFthrowssomeerrorswhenusingfirstChild.firstChild//if(this.rows[i].cells[0].firstChild&&this.rows[i].cells[0].firstChild.firstChild){this.rows[i].cells[0].firstChild.firstChild.innerHTML=""+(i+1);//}//[D]this.rows[i].dHeight=dojo.html.getInnerHeight(this.rows[i]);this.rows[i].dHeight=dojo.position(this.rows[i]).h;for(varj=0;j<this.rows[i].cells.length;j++){//[D]vartmpW=dojo.html.getInnerWidth(this.rows[i].cells[j].firstChild)+(dojo.render.html.ie?2:3);vartmpW=dojo.position(this.rows[i].cells[j].firstChild).w+(dojo.isIE?2:3);//[D]vartmpH=dojo.html.getInnerHeight(this.rows[i].cells[j].firstChild)+(dojo.render.html.ie?3:3);vartmpH=dojo.position(this.rows[i].cells[j].firstChild).h+(dojo.isIE?3:3);this.rows[i].cells[j].firstChild.dWidth=tmpW;this.rows[i].cells[j].firstChild.style.width=tmpW;this.rows[i].cells[j].firstChild.dHeight=tmpH;this.rows[i].cells[j].firstChild.style.height=tmpH;//varbgColor=dojo.html.getBackgroundColor(this.rows[i].cells[j].firstChild);varbgColor=dojo.style(this.rows[i].cells[j].firstChild,"backgroundColor");//[D]this.rows[i].cells[j].firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);this.rows[i].cells[j].firstChild.dBackgroundColor=bgColor;//dojo.html.disableSelection(this.rows[i].cells[j]);dojo.setSelectable(this.rows[i].cells[j],false);//dojo.html.disableSelection(this.rows[i].cells[j].firstChild);dojo.setSelectable(this.rows[i].cells[j].firstChild,false);}varcucu=this.rows[i].cells[0].getElementsByTagName("div");for(varss=0;ss<cucu.length;ss++){cucu[ss].style.width="20px";}this.rows[i].cells[0].style.width="20px";this.rows[i].cells[0].firstChild.style.height="20px";this.rows[i].cells[0].firstChild.firstChild.style.height="18px";this.rows[i].cells[0].firstChild.firstChild.nextSibling.style.height="2px";}varths=this.domNode.getElementsByTagName("TH");ths[0].style.width="20px";for(vari=1;i<ths.length;i++){ths[i].dCellIndex=i-1;//[D]ths[i].dWidth=dojo.html.getInnerWidth(ths[i]);ths[i].dWidth=dojo.position(ths[i]).w;if(ths[i].firstChild&&ths[i].firstChild.firstChild){ths[i].firstChild.firstChild.innerHTML=String.fromCharCode("A".charCodeAt(0)+i-1);}dojo.setSelectable(ths[i],false);dojo.setSelectable(ths[i].firstChild,false);dojo.setSelectable(ths[i].firstChild.firstChild,false);}},/***Createstheinputelementtodisplaywheneditingacell*/createInputElem:function(){if(this.inputElem==null){this.inputElem=document.createElement("input");with(this.inputElem){type="text";className="sheetInput";style.position="absolute";style.display="none";tdElem=null;}document.body.appendChild(this.inputElem);dojo.setSelectable(this.inputElem,false);}},/***Handlesonmousedownwhichcancauseseveralrelevanteventsforspreadsheet:focusing,selection,resizing*/onMouseDown:function(e){vartarget=(e.target)?e.target:e.srcElement;//[D]varinputElem=dojo.html.getParentByType(e.target,"INPUT");varinputElem=dijit.range.getAncestor(target,/INPUT/i);if(inputElem&&dojo.hasClass(inputElem,"sheetInput")){return;}this.deselectAll();//[D]varcurrentTDElem=dojo.html.getParentByType(e.target,"TD");varcurrentTDElem=dijit.range.getAncestor(target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.isSelectingCells=true;this.selectionStartCell=currentTDElem;this.selectCellByTD(this.selectionStartCell,true);e.preventDefault();}//[D]varcurrentDIVElem=dojo.html.getParentByType(e.target,"DIV");varcurrentDIVElem=dijit.range.getAncestor(target,/DIV/i);if(currentDIVElem&&dojo.hasClass(currentDIVElem,"horizontalResizer")){this.isResizingHorizontal=true;varpos=this.getCursorPosition(e);this.resizeOrigXPos=pos.x;//[D]this.resizeOrigTH=dojo.html.getParentByType(e.target,"TH");this.resizeOrigTH=dijit.range.getAncestor(target,/TH/i);}if(currentDIVElem&&dojo.hasClass(currentDIVElem,"verticalResizer")){this.isResizingVertical=true;varpos=this.getCursorPosition(e);this.resizeOrigYPos=pos.y;//[D]this.resizeOrigTD=dojo.html.getParentByType(e.target,"TD");this.resizeOrigTD=dijit.range.getAncestor(target,/TD/i);}if(!this.isResizingHorizontal&&!this.isResizingVertical){//[D]varcurrentTH=dojo.html.getParentByType(e.target,"TH");varcurrentTH=dijit.range.getAncestor(target,/TH/i);if(currentTH){this.isSelectingColumns=true;this.selectionStartColumn=currentTH.dCellIndex;this.selectColumns(this.selectionStartColumn);}//[D]varcurrentTDRowHeader=dojo.html.getParentByType(e.target,"TD");varcurrentTDRowHeader=dijit.range.getAncestor(target,/TD/i);if(currentTDRowHeader&&dojo.hasClass(currentTDRowHeader,"sheetRow1stCell")){this.isSelectingRows=true;this.selectionStartRow=this.getCellRow(currentTDRowHeader);this.selectRows(this.selectionStartRow);}}},/***Handlesonmousemove-usefulwhenresizingtodinamicallyresizeasmousemoves*/onMouseMove:function(e){if(this.isResizingHorizontal){this.resizeCol(e,false);}if(this.isResizingVertical){this.resizeRow(e,false);}},/***Handlesonmouseover-tokeeptrackoftheselectionprocess*/onMouseOver:function(e){if(this.isSelectingCells){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.deselectAll();this.selectRegion(this.getCellCol(currentTDElem),this.getCellCol(this.selectionStartCell),this.getCellRow(currentTDElem),this.getCellRow(this.selectionStartCell),true);}}if(this.isSelectingColumns){//themousemaymoveoverTHsorTDs.HoweverweshoulddetectineachcasethecolumnvarcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){varselectionEndColumn=this.getCellCol(currentTDElem);this.selectColumns(selectionEndColumn);}else{varcurrentTHElem=dijit.range.getAncestor(e.target,/TH/i);if(currentTHElem){varselectionEndColumn=currentTHElem.dCellIndex;this.selectColumns(selectionEndColumn);}}}if(this.isSelectingRows){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&(dojo.hasClass(currentTDElem,"sheetCell")||dojo.hasClass(currentTDElem,"sheetRow1stCell"))){varselectionEndRow=this.getCellRow(currentTDElem);this.selectRows(selectionEndRow);}}},/***Handlesonmouseup-eitherselectionofresizinghavefinished*/onMouseUp:function(e){if(this.isSelectingCells){//unselectonlyifthemouseupoccuredonthesamecellif(this.selectionStartCell&&this.selectionStartCell==dijit.range.getAncestor(e.target,/TD/i)){this.selectCellByTD(this.selectionStartCell,false);this.focusOn(this.selectionStartCell);}this.isSelectingCells=false;}if(this.isResizingHorizontal){this.resizeCol(e,true);this.isResizingHorizontal=false;}if(this.isResizingVertical){this.resizeRow(e,true);this.isResizingVertical=false;}if(this.isSelectingColumns){this.isSelectingColumns=false;}if(this.isSelectingRows){this.isSelectingRows=false;}},/***Ondblclick-theeditingboxisshown*/onDblClick:function(e){varcurrentTDElem=dijit.range.getAncestor(e.target,/TD/i);if(currentTDElem&&dojo.hasClass(currentTDElem,"sheetCell")){this.deselectAll();this.showInputOverTD(currentTDElem);}},/***Onkeypress-managesdelete,enter,backspace,esc,spacekeys*/onKeyPress:function(e){varkeyCode=e.keyCode==0?e.which:e.keyCode;vark=dojo.keys;varkeyHandled=false;if(keyCode==k.KEY_ESCAPE){this.hideInput(true);keyHandled=true;}if(keyCode==k.KEY_BACKSPACE){this.eraseCurrentCellContent();}if(keyCode==k.KEY_DELETE){this.eraseCurrentCellContent();}if(keyCode==k.KEY_ENTER){if(!this.isEditing){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);this.showInputOverTD(tdElem);keyHandled=true;}else{this.moveFocus(0,1);keyHandled=true;}}if(keyCode==k.KEY_SPACE||(keyCode>=41&&keyCode<=44)||keyCode>=47){if(!this.isEditing){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);this.showInputOverTD(tdElem);if(!dojo.isIE){this.inputElem.value=String.fromCharCode(keyCode);}}}if(keyHandled==true){e.preventDefault();e.stopPropagation();}},/***onKeyUp-handlesup/right/down/leftarrows*/onKeyUp:function(e){varkeyCode=e.keyCode==0?e.which:e.keyCode;//vark=dojo.event.browser.keys;vark=dojo.keys;varkeyHandled=false;if(keyCode==k.KEY_DOWN_ARROW){if(!this.isEditing){this.moveFocus(0,1);keyHandled=true;}}if(keyCode==k.KEY_UP_ARROW){if(!this.isEditing){this.moveFocus(0,-1);keyHandled=true;}}if(keyCode==k.KEY_LEFT_ARROW){if(!this.isEditing){this.moveFocus(-1,0);keyHandled=true;}}if(keyCode==k.KEY_RIGHT_ARROW){if(!this.isEditing){this.moveFocus(1,0);keyHandled=true;}}if(keyHandled==true){e.preventDefault();e.stopPropagation();}},/***Movesfocustothespecifiedcell*@deltaXdeltamovementoncolumns*@deltaYdeltamovementonrows*/moveFocus:function(deltaX,deltaY){varnewCol=this.currentFocusedCol;varanyChange=false;if(newCol+deltaX<this.spreadsheetWidth&&newCol+deltaX>=0){newCol=newCol+deltaX;anyChange=true;}varnewRow=this.currentFocusedRow;if(newRow+deltaY<this.spreadsheetHeight&&newRow+deltaY>=0){newRow=newRow+deltaY;anyChange=true;}if(anyChange){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.currentFocusedCol=newCol;this.currentFocusedRow=newRow;this._focus(this.currentFocusedCol,this.currentFocusedRow);}},/***Focusesonagivenelement*@paramelemthe<TD>elementtofocuson*/focusOn:function(elem){var_col=this.getCellCol(elem);var_row=this.getCellRow(elem);if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){this.focusAt(_col,_row);}},/***Focusesatagivenlocation*@param_colthecolcoordinatewheretofocus*@param_rowtherowcoordinatewheretofocus*/focusAt:function(_col,_row){if(_row>=this.spreadsheetHeight){_row=this.spreadsheetHeight-1;}if(_col>=this.spreadsheetWidth){_col=this.spreadsheetWidth-1;}this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.currentFocusedCol=_col;this.currentFocusedRow=_row;this.selectionStartCell=this.getCell(_col,_row);this._focus(this.currentFocusedCol,this.currentFocusedRow);},/***Internalfnwhichactuallydoesthefocusing*@param_colthecolcoordinatewheretofocus*@param_rowtherowcoordinatewheretofocus*/_focus:function(_col,_row){if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){var_tdElem=this.getCell(_col,_row);var_italic=false;var_bold=false;var_underline=false;if(typeof(_tdElem.styleList)!="undefined"){_bold=_tdElem.styleList[this.FORMATTING_TYPES.BOLD]?_tdElem.styleList[this.FORMATTING_TYPES.BOLD]:false;_italic=_tdElem.styleList[this.FORMATTING_TYPES.ITALIC]?_tdElem.styleList[this.FORMATTING_TYPES.ITALIC]:false;_underline=_tdElem.styleList[this.FORMATTING_TYPES.UNDERLINE]?_tdElem.styleList[this.FORMATTING_TYPES.UNDERLINE]:false;}this._fireEvent("setFormatting",_bold,_italic,_underline);varw=_tdElem.firstChild.dWidth;varh=_tdElem.firstChild.dHeight;_tdElem.firstChild.style.width=this.toPx(w-(dojo.isIE?0:4));_tdElem.firstChild.style.height=this.toPx(h-(dojo.isIE?0:4));dojo.addClass(_tdElem.firstChild,"focused");}}},/***Unfocusesthecellatagivenposition*@param_colthecolcoordinatewheretounfocus*@param_rowtherowcoordinatewheretounfocus*/unfocus:function(_col,_row){this.hideInput();if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){var_tdElem=this.getCell(_col,_row);varw=_tdElem.firstChild.dWidth;varh=_tdElem.firstChild.dHeight;_tdElem.firstChild.style.width=this.toPx(w);_tdElem.firstChild.style.height=this.toPx(h);dojo.removeClass(_tdElem.firstChild,"focused");}}},/***Selectsaregionofthespreadsheet*@paramcol1thestartcol*@paramcol2theendcol*@paramrow1thestartrow*@paramrow2theendrow*@param_selectwhethertoselectordeselecttheregion*/selectRegion:function(col1,col2,row1,row2,_select){varminCol=col1<col2?col1:col2;varmaxCol=col1>col2?col1:col2;varminRow=row1<row2?row1:row2;varmaxRow=row1>row2?row1:row2;this.lastSelectedRegion=[minCol,maxCol,minRow,maxRow];for(vari=minCol;i<=maxCol;i++){for(varj=minRow;j<=maxRow;j++){this.selectCell(i,j,_select);}}if(this.selectionStartCell){this.focusOn(this.selectionStartCell);}if(!_select){this.lastSelectedRegion=null;}},/***SelectsacellgiventheHTMLelement*@param_tdElemthe<TD>elementtoselect*@param_selectwhethertoselectordeselecttheHTMLelement*/selectCellByTD:function(_tdElem,_select){if(typeof(_tdElem)!="undefined"){this.selectCell(this.getCellCol(_tdElem),this.getCellRow(_tdElem),_select);}},/***Selectsordeselectsacell.Selectionmeanschangingthecolortoalighter/darkerbluedependingonB's value (B from RGB)*@param_colthecolumn(0-n,where0correspondstotheAcolumnofthespreadsheetwhichisactuallythesecondcolumnofthetable*@param_rowtherow(0-n,0-correspondssimilarlytorow1)*@param_selectwhethertoselectordeselectthecell*/selectCell:function(_col,_row,_select){if(typeof(_col)!="undefined"&&typeof(_row)!="undefined"){if(_row<this.spreadsheetHeight&&_col<this.spreadsheetWidth){vartdElem=this.getCell(_col,_row);if(_select){//varbgColor=dojo.html.getBackgroundColor(tdElem.firstChild);varbgColor=dojo.style(tdElem.firstChild,"backgroundColor");//tdElem.firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//bgColor[0]=parseInt(bgColor[0]);//bgColor[1]=parseInt(bgColor[1]);//bgColor[2]=parseInt(bgColor[2]);//bgColor[0]=bgColor[0]>128?bgColor[0]-32:bgColor[0]+32;//bgColor[1]=bgColor[1]>128?bgColor[1]-32:bgColor[1]+32;//[D]tdElem.firstChild.style.backgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//tdElem.firstChild.style.backgroundColor=dojo.gfx.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);tdElem.firstChild.style.backgroundColor=bgColor;}else{tdElem.firstChild.style.backgroundColor=tdElem.firstChild.dBackgroundColor;}}}},/***Selectsanentirecolumn*@paramidxtheindexofthecolumntobeselected*@param_selectwhethertoselectordeselectthecolumn*/selectColumn:function(idx,_select){for(vari=0;i<this.spreadsheetHeight;i++){this.selectCell(idx,i,_select);}},/***Selectsanintervalofcolumns*@selectionEndColumnthelastcolumnoftheselection.Thefirstoneismaintainedatmouseevents*/selectColumns:function(selectionEndColumn){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.deselectAll();this.lastSelectedColumns=[];varminCol=selectionEndColumn<this.selectionStartColumn?selectionEndColumn:this.selectionStartColumn;varmaxCol=selectionEndColumn>this.selectionStartColumn?selectionEndColumn:this.selectionStartColumn;for(vari=minCol;i<=maxCol;i++){this.addColumnToSelection(i);this.selectColumn(i,true);}//selectfirstcelloffirstcolumnxthis.focusAt(this.selectionStartColumn,0);},/***Addsacolumntothelistofcolumnstobeselected*@paramidxtheindexofthecolumntobeselected*/addColumnToSelection:function(idx){this.lastSelectedColumns[this.lastSelectedColumns.length]=idx;},/***Selectsanentirerow*@paramidxtheindexoftherowtobeselected*@param_selectwhethertoselectordeselecttherow*/selectRow:function(idx,_select){for(vari=0;i<this.spreadsheetWidth;i++){this.selectCell(i,idx,_select);}},/***Selectsanintervalofrows*@selectionEndRowthelastrowoftheselection.Thefirstoneismaintainedatmouseevents*/selectRows:function(selectionEndRow){this.deselectAll();this.lastSelectedRows=[];varminRow=selectionEndRow<this.selectionStartRow?selectionEndRow:this.selectionStartRow;varmaxRow=selectionEndRow>this.selectionStartRow?selectionEndRow:this.selectionStartRow;for(vari=minRow;i<=maxRow;i++){this.addRowToSelection(i);this.selectRow(i,true);}//selectfirstcelloffirstrowthis.focusAt(1,this.selectionStartRow);},/***Addsarowtothelistofrowstobeselected*@paramidxtheindexoftherowtobeselected*/addRowToSelection:function(idx){this.lastSelectedRows[this.lastSelectedRows.length]=idx;},/***Returnstheselectionmode.Possiblevaluesare:SELECTION_MODES.RECTANGLEandSELECTION_MODES.RANDOM*RandommodewillbeusedwhenselectingrandomcellsusingSHIFT&CTRL.Notsupportedyet.*@returntheselectionmode*/getSelectionMode:function(){returnthis.selectionMode;},/***Returnsalistofselectedcells-tobeusedwhenselectionmodeisSELECTION_MODES.RANDOM*@returnalistofselectedcells*/getSelection:function(){varselectedCells=newArray();if(this.getSelectionMode()==this.SELECTION_MODES.RECTANGLE){if(this.lastSelectedRegion!=null){for(vari=this.lastSelectedRegion[0];i<=this.lastSelectedRegion[1];i++){for(varj=this.lastSelectedRegion[2];j<=this.lastSelectedRegion[3];j++){selectedCells[selectedCells.length]=[i,j];}}}else{selectedCells[selectedCells.length]=[this.currentFocusedCol,this.currentFocusedRow];}}returnselectedCells;},/***Returnstheselectionrectangle-tobeusedwhenselectionmodeisSELECTION_MODES.RECTANGLE*@returnanarraywith4coordinates:[colStart,colEnd,rowStart,rowEnd]*/getSelectionRectangle:function(){if(this.lastSelectedRegion&&this.lastSelectedRegion!=null){returnthis.lastSelectedRegion;}else{return[this.currentFocusedCol,this.currentFocusedCol,this.currentFocusedRow,this.currentFocusedRow];}},/***Deselectseverything*/deselectAll:function(){this.unfocus(this.currentFocusedCol,this.currentFocusedRow);this.resetSelectedColumns();this.resetSelectedRows();if(this.lastSelectedRegion&&this.lastSelectedRegion!=null){this.selectRegion(this.lastSelectedRegion[0],this.lastSelectedRegion[1],this.lastSelectedRegion[2],this.lastSelectedRegion[3],false);}},/***Deselectsselectedcolumnsifany*/resetSelectedColumns:function(){for(vari=0;i<this.lastSelectedColumns.length;i++){this.selectColumn(this.lastSelectedColumns[i],false);}this.lastSelectedColumns=[];},/***Deselectsselectedrowsifany*/resetSelectedRows:function(){for(vari=0;i<this.lastSelectedRows.length;i++){this.selectRow(this.lastSelectedRows[i],false);}this.lastSelectedRows=[];},/***Resizesacolumn*@parametheDOMevent*@paramstorePositionwhethertostorepositionornot(usedwhenthemouseisstillmoving)*/resizeCol:function(e,storePosition){varpos=this.getCursorPosition(e);varnewX=pos.x;varcurrentCol=this.resizeOrigTH.dCellIndex+1;//if(currentResizedCol){vardelta=newX-this.resizeOrigXPos;varnewWidth=this.resizeOrigTH.dWidth+delta;if(newWidth<this.MINIMUM_CELL_WIDTH){newWidth=this.MINIMUM_CELL_WIDTH;}this.resizeOrigTH.style.width=this.toPx(newWidth);this.resizeOrigTH.firstChild.style.width=this.toPx(newWidth-3);this.resizeOrigTH.firstChild.firstChild.style.width=this.toPx(newWidth-5);for(vari=0;i<this.rows.length;i++){this.rows[i].cells[currentCol].firstChild.style.width=this.toPx(newWidth);}if(storePosition){this.resizeOrigTH.dWidth=newWidth;for(vari=0;i<this.rows.length;i++){this.rows[i].cells[currentCol].firstChild.dWidth=newWidth;}this._focus(this.currentFocusedCol,this.currentFocusedRow);}//}},/***Resizesarow*@parametheDOMevent*@paramstorePositionwhethertostorepositionornot(usedwhenthemouseisstillmoving)*/resizeRow:function(e,storePosition){varpos=this.getCursorPosition(e);varnewY=pos.y;varcurrentRow=this.getCellRow(this.resizeOrigTD);vardelta=newY-this.resizeOrigYPos;varnewHeight=this.rows[currentRow].dHeight+delta+2;if(newHeight<this.MINIMUM_CELL_HEIGHT){newHeight=this.MINIMUM_CELL_HEIGHT;}//resize1stcell(number+verticalresizer)this.rows[currentRow].cells[0].style.height=this.toPx(newHeight);this.rows[currentRow].cells[0].firstChild.firstChild.style.height=this.toPx(newHeight-(dojo.isIE?2:0));for(vari=1;i<this.rows[0].cells.length;i++){this.rows[currentRow].cells[i].firstChild.style.height=this.toPx(newHeight);}if(storePosition){this.rows[currentRow].dHeight=newHeight;for(vari=1;i<this.rows[0].cells.length;i++){this.rows[currentRow].cells[i].firstChild.dHeight=newHeight;}this._focus(this.currentFocusedCol,this.currentFocusedRow);}},/***Displaystheinputelementatagivenlocation*@param_tdElemthe<TD>elementoverwhichtheinputelementhastobedisplayed*/showInputOverTD:function(_tdElem){this.isEditing=true;//varpos=dojo.html.getAbsolutePosition(_tdElem,true);varpos=dojo.coords(_tdElem);with(this.inputElem){tdElem=_tdElem;//[D]style.width=dojo.html.getInnerWidth(_tdElem)+8;//style.width=dojo.html.getBorderBox(_tdElem).width+8;style.width=dojo.position(_tdElem).w+8;//[D]style.height=dojo.html.getInnerHeight(_tdElem)+8;style.height=dojo.position(_tdElem).h+8;style.left=pos.x-4;style.top=pos.y-4;style.zIndex=100;style.display="";if(tdElem!=null){if(typeof(tdElem.formula)=="undefined"){value="";}else{value=_tdElem.formula;}/*if(tdElem.cellType==this.CELL_TYPES.FORMULA){value=tdElem.formula;}else{value=tdElem.firstChild.innerHTML;}*/}else{value="";}oldValue=value;if(typeof(oldValue)=="undefined"||oldValue=="undefined"){oldValue="";}focus();}dijit.selectInputText(this.inputElem);},/***Hidestheinputelementandsavesthevalue*@paramisCancelwhethertocancelornotthemodificationstothecell*/hideInput:function(isCancel){this.isEditing=false;with(this.inputElem){//preventthisfromexecutingtwice-changethevalueandhidetheinputonlyifinputisvisibleif(style.display==""){if(tdElem!=null){if(isCancel){//tdElem.firstChild.innerHTML=oldValue;tdElem.formula=oldValue;}else{//tdElem.firstChild.innerHTML=value;tdElem.formula=value;}this.evalFormula(tdElem,true);}value="";style.display="none";}}},/***Deletesthecontentofthecurrentfocusedcell*/eraseCurrentCellContent:function(){vartdElem=this.getCell(this.currentFocusedCol,this.currentFocusedRow);tdElem.firstChild.innerHTML="";},/***Insertsanewcolumnbeforethecolumnofthecurrentfocusedcell*/insertColumnBefore:function(){try{varcolumnToInsertBefore=this.currentFocusedCol+1;varthead=this.domNode.getElementsByTagName("THEAD")[0];varths=thead.getElementsByTagName("TH");varnewTH=ths[columnToInsertBefore].cloneNode(true);//dojo.html.insertBefore(newTH,ths[columnToInsertBefore]);dojo.place(newTH,ths[columnToInsertBefore],"before");for(vari=0;i<this.rows.length;i++){varnewTD=this.rows[i].cells[columnToInsertBefore].cloneNode(true);//dojo.html.insertBefore(newTD,this.rows[i].cells[columnToInsertBefore]);dojo.place(newTD,this.rows[i].cells[columnToInsertBefore],"before");}this.resetSpreadsheet();//resetcell's formatting and contentif(columnToInsertBefore>=1){for(vari=0;i<this.rows.length;i++){this.rows[i].cells[columnToInsertBefore].firstChild.innerHTML="";this.unfocus(columnToInsertBefore,i);this.selectCell(columnToInsertBefore,i,false);}}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewcolumnafterthecolumnofthecurrentfocusedcell*/insertColumnAfter:function(){try{varthead=this.domNode.getElementsByTagName("THEAD")[0];varths=thead.getElementsByTagName("TH");varnewTH=ths[this.currentFocusedCol].cloneNode(true);//dojo.html.insertAfter(newTH,ths[this.currentFocusedCol]);dojo.place(newTH,ths[this.currentFocusedCol],"after");for(vari=0;i<this.rows.length;i++){varnewTD=this.rows[i].cells[this.currentFocusedCol].cloneNode(true);//dojo.html.insertAfter(newTD,this.rows[i].cells[this.currentFocusedCol]);dojo.place(newTD,this.rows[i].cells[this.currentFocusedCol],"after");}this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentif(this.currentFocusedCol>=1){for(vari=0;i<this.rows.length;i++){this.rows[i].cells[this.currentFocusedCol+1].firstChild.innerHTML="";this.unfocus(this.currentFocusedCol+1,i);this.selectCell(this.currentFocusedCol+1,i,false);}}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewrowbeforetherowofthecurrentfocusedcell*/insertRowBefore:function(){try{varnewTR=this.rows[this.currentFocusedRow].cloneNode(true);//dojo.html.insertBefore(newTR,this.rows[this.currentFocusedRow]);dojo.place(newTR,this.rows[this.currentFocusedRow],"before");this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentfor(vari=1;i<newTR.cells.length;i++){newTR.cells[i].firstChild.innerHTML="";this.unfocus(i,this.currentFocusedRow);this.selectCell(i,this.currentFocusedRow,false);}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Insertsanewrowaftertherowofthecurrentfocusedcell*/insertRowAfter:function(){try{varnewTR=this.rows[this.currentFocusedRow].cloneNode(true);//dojo.html.insertAfter(newTR,this.rows[this.currentFocusedRow]);dojo.place(newTR,this.rows[this.currentFocusedRow],"after");this.rows=this.loadRows();this.resetSpreadsheet();//resetcell's formatting and contentfor(vari=1;i<newTR.cells.length;i++){newTR.cells[i].firstChild.innerHTML="";this.unfocus(i,this.currentFocusedRow+1);this.selectCell(i,this.currentFocusedRow+1,false);}}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}},/***Removeselectedrows*/removeRows:function(){varrowsToRemove=[];if(this.lastSelectedRows.length>0){for(vari=0;i<this.lastSelectedRows.length;i++){rowsToRemove[rowsToRemove.length]=this.lastSelectedRows[i];}}else{rowsToRemove[rowsToRemove.length]=this.currentFocusedRow;}varrowStr="";for(vari=0;i<rowsToRemove.length;i++){rowStr+="\t"+this.rows[rowsToRemove[i]].cells[0].firstChild.firstChild.innerHTML+"\n";}if(confirm("Are you sure you want to remove "+(rowsToRemove.length==1?"this row?\n":"these rows?\n")+rowStr)){try{for(vari=0;i<rowsToRemove.length;i++){dojo.doc.documentElement.removeNode(this.rows[rowsToRemove[i]]);}this.resetSpreadsheet();//focusontheclosestuppercellthis.focusAt(this.currentFocusedCol,this.currentFocusedRow);}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}}},/***Removeselectedcols*/removeCols:function(){varcolumnsToRemove=[];if(this.lastSelectedColumns.length>0){for(vari=0;i<this.lastSelectedColumns.length;i++){columnsToRemove[columnsToRemove.length]=this.lastSelectedColumns[i];}}else{columnsToRemove[columnsToRemove.length]=this.currentFocusedCol;}varths=this.domNode.getElementsByTagName("TH");varcolStr="";for(vari=0;i<columnsToRemove.length;i++){colStr+="\t"+ths[columnsToRemove[i]].firstChild.firstChild.innerHTML+"\n";}if(confirm("Are you sure you want to remove "+(columnsToRemove.length==1?"this column?\n":"these columns?\n")+colStr)){try{for(vari=0;i<columnsToRemove.length;i++){dojo.doc.documentElement.removeNode(ths[columnsToRemove[i]]);for(varj=0;j<this.rows.length;j++){dojo.doc.documentElement.removeNode(this.rows[j].cells[columnsToRemove[i]]);}}this.resetSpreadsheet();//focusontheclosestuppercellthis.focusAt(this.currentFocusedCol,this.currentFocusedRow);}catch(e){alert(e+" $$ "+e.name+" $$ "+e.message);}}},/***Appliesoneoftheavailableformattingtypestothecell(FORMATTING_TYPES.FONT,FORMATTING_TYPES.FONT_SIZE,etc)*@paramstyleTypethestyletochange*@paramstyleValuethevalueforthestyle*/formatSelectedCells:function(styleType,styleValue){varsel=this.getSelection();//sel[i][0]givesthecolumn,sel[i][1]givestherowfor(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][0],sel[i][1]);this.addStyleToCell(styleType,styleValue,tdElem);this.applyStylesToCell(tdElem);}},/***Addsastyletothelistofstyles*@paramstyleTypethestyletochange*@paramstyleValuethevalueforthestyle*@paramtdElemthe<TD>elementtobeformatted*/addStyleToCell:function(styleType,styleValue,tdElem){if(typeof(tdElem.styleList)=="undefined"){tdElem.styleList=newArray();}//tdElem.styleList.add({style:styleType,value:styleValue});tdElem.styleList[styleType]=styleValue;},removeStyleForCell:function(style,tdElem){},/***Appliesthestylesforacell*@paramtdElemthe<TD>elementforwhichstylesareapplied*/applyStylesToCell:function(tdElem){varstyles=tdElem.styleList;if(typeof(styles)!="undefined"){//fontvarfont=styles[this.FORMATTING_TYPES.FONT];if(typeof(font)!="undefined"){tdElem.firstChild.style.fontFamily=font;}//fontsizevarfont_size=styles[this.FORMATTING_TYPES.FONT_SIZE];if(typeof(font_size)!="undefined"){tdElem.firstChild.style.fontSize=font_size;}//COLORvarcolor=styles[this.FORMATTING_TYPES.COLOR];if(typeof(color)!="undefined"){tdElem.firstChild.style.color=color;}//BG_COLORvarbgColor=styles[this.FORMATTING_TYPES.BG_COLOR];if(typeof(bgColor)!="undefined"){tdElem.firstChild.style.backgroundColor=bgColor;//varbgColor=dojo.html.getBackgroundColor(tdElem.firstChild);varbgColor=dojo.style(tdElem.firstChild,"backgroundColor");//[D]tdElem.firstChild.dBackgroundColor=dojo.graphics.color.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);//tdElem.firstChild.dBackgroundColor=dojo.gfx.rgb2hex(bgColor[0],bgColor[1],bgColor[2]);tdElem.firstChild.dBackgroundColor=bgColor;}//BOLDvarbold=styles[this.FORMATTING_TYPES.BOLD];if(typeof(bold)!="undefined"){if(bold){tdElem.firstChild.style.fontWeight="bold";}else{tdElem.firstChild.style.fontWeight="";}}//ITALICvaritalic=styles[this.FORMATTING_TYPES.ITALIC];if(typeof(italic)!="undefined"){if(italic){tdElem.firstChild.style.fontStyle="italic";}else{tdElem.firstChild.style.fontStyle="";}}//UNDERLINEvarunderline=styles[this.FORMATTING_TYPES.UNDERLINE];if(typeof(underline)!="undefined"){if(underline){tdElem.firstChild.style.textDecoration="underline";}else{tdElem.firstChild.style.textDecoration="";}}}},/***Appliesaformula*@paramformulathenameoftheformula*/applyFormula:function(functionName){//minXandmaxYareusedtodeterminewheretheresultwillbewritten(inthebottom-leftcornerofthe//mostcomprehensiverectangle)varminCol=1000000;varmaxRow=-1;varsel=this.getSelection();//sel[i][0]givesthecolumn,sel[i][1]givestherowfor(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][1],sel[i][0]);minCol=minCol>sel[i][0]?sel[i][0]:minCol;maxRow=maxRow<sel[i][1]?sel[i][1]:maxRow;}//gettheleft-bottommostcellvarresultCell=this.getCell(minCol,maxRow+1);if(resultCell){if(this.getSelectionMode()==this.SELECTION_MODES.RECTANGLE){varcellColStart=this.fromArrToCellNotation(this.lastSelectedRegion[0],this.lastSelectedRegion[2]);varcellColStop=this.fromArrToCellNotation(this.lastSelectedRegion[1],this.lastSelectedRegion[3]);resultCell.formula="="+functionName+"("+cellColStart+":"+cellColStop+")";this.evalFormula(resultCell,true);}else{//onlyrectangleselectionmodeissupportedfornow,sowillNEVERgethereresultCell.formula="="+functionName+"(";for(vari=0;i<sel.length;i++){vartdElem=this.getCell(sel[i][1],sel[i][0]);varcellCol=String.fromCharCode("A".charCodeAt(0)+sel[i][0]-1);resultCell.formula=""+cellCol+(sel[i][1]+1)+(i==sel.length-1?"":",");}resultCell.formula=")";this.evalFormula(resultCell,true);}}},/***Checkstheentiregraphforcircularities*@throwsanexceptionifcircularitiesaredetected*/checkCircularities:function(){varstack=newArray();try{for(vari=0;i<this.ssGraph.length;i++){stack.push(i);this.checkCircularitiesPerNode(stack,i);stack.pop();}}catch(e){throw(e);}},/***Checksthegraphforcircularitiesgivenastartvertex*@throwsanexceptionifcircularitiesaredetected*/checkCircularitiesFromNode:function(node){varstack=newArray();try{stack.push(node);this.checkCircularitiesPerNode(stack,node);stack.pop();}catch(e){throw(e+" when evaluating cell "+this.fromGraphNodeToCellNotation(node));}},/***Recursivefunctionthatchecksforagivennodeifthereisacircularityinthegraph*@stackthestackofvisitednodes*@paramnodetheindexofthenodeinthematrix(0,1,2...mxn)wherem=numcolsandn=numrows*@throwsexceptionifcirculardependenciesaredetected*/checkCircularitiesPerNode:function(stack,node){for(vari=0;i<this.ssGraph.length;i++){//there's no need to avoid nodeX-nodeX relationships since they'reallgoingtobe0if(this.ssGraph[node][i]==1){//checkwhetherthestackalreadycontainsnodeifor(vark=0;k<stack.length;k++){if(stack[k]==i){throw"Circular Dependency Detected";//forcell:" + fromGraphNodeToCellNotation(i);}}stack.push(i);this.checkCircularitiesPerNode(stack,i);stack.pop();}}},/***Re-evaluatedependentcells.Thismethodalsochecksforcirculardependencies.*@throwsanexceptionifcircularitiesaredetected*/reevalDependentCells:function(node){varstack=newArray();try{stack.push(node);this.reevalDependentCellsPerNode(stack,node);stack.pop();}catch(e){throw(e+" when evaluating dependencies cell "+this.fromGraphNodeToCellNotation(node));}},/***Recursivefunctionfordetectingcellsdependentoncurrentcellandreevaluatingthem*@stackthestackofvisitednodes*@paramnodetheindexofthenodeinthematrix(0,1,2...mxn)wherem=numcolsandn=numrows*@throwsexceptionifcirculardependenciesaredetected*/reevalDependentCellsPerNode:function(stack,node){for(vari=0;i<this.ssGraph.length;i++){if(this.ssGraph[i][node]==1){for(vark=0;k<stack.length;k++){if(stack[k]==i){throw"Circular Dependency Detected";//forcell:" + fromGraphNodeToCellNotation(i);}}//re-evaluatecell's valuevarcell=this.getCellByCellNotation(this.fromGraphNodeToCellNotation(i));this.evalFormula(cell,true,true);stack.push(i);this.reevalDependentCellsPerNode(stack,i);stack.pop();}}},/***Returnsanarraycontaining(col,row)astheyareretrievedfromthecellnotation(A2,B33,etc).*Theindexesarerelativetothecellsspreadsheet(col0-isactuallythesecondcolumn-1stoneistheheader)*@paramcellNotationastringrepresentingthecellnotation*@returnanobjectwithtwoproperties:colandrow*/fromCellNotationToArr:function(cellNotation){varletter=""+cellNotation.match(/[a-zA-Z]*/);varnumber=""+cellNotation.match(/[0-9]+/);//buildtheindicesforthecellvarcol=this.fromCharToIdx(letter);varrow=parseInt(number)-1;return{"col":col,"row":row};},/***Createsacellnotation,givenacellandarow.Thecellandrowmuststartfrom0(thismeans,youcan't pass*rowIndexandcellIndexpropertiesof<TR>and<TD>elements.Youneedtohandleconversionfromtheseproperties*toproperindexes(usuallythisistransparentlyhandledbygetCellRowandgetCellCol).A(0,0)willbeA1incell*notation*@paramcolthecolumnindex(for0avalueof'A'willbereturned)*@paramrowtherowindex(for0avalueof1willbereturned)*@returnastringrepresentingthecellnotationA1,C5,etc*/fromArrToCellNotation:function(col,row){returnthis.fromIdxToChar(col)+(row+1);},/***Utilityfunctionfortransformingacharcodetoit's correspondent in number (a-0, b-1,...)*@paramchthechar*@returnanumber*/fromCharToIdx:function(ch){returnch.toLowerCase().charCodeAt(0)-"a".charCodeAt(0);},/***Utilityfunctionfortransformingandindextoitscorrespondingchar(0-a,1-b,...)*@idxtheindex*@returnanuppercasestringwithoneletter*/fromIdxToChar:function(idx){returnString.fromCharCode("a".charCodeAt(0)+idx).toUpperCase();},/***Returnsthecellnotationforanodeinthegraphofdependencies*@paramnodeIdxanumberrepresentingthenodeinthegraph*@returnastringrepresentingthecellnotationA1,C5,etc*/fromGraphNodeToCellNotation:function(nodeIdx){varrow=parseInt(nodeIdx/this.spreadsheetWidth);varcol=nodeIdx%this.spreadsheetWidth;returnthis.fromArrToCellNotation(col,row);},/***Returnsthenodeinthegraphofdependenciesforacolumn/row*@paramcolthecolumn*@paramrowtherow*@returnanumberrepresentingthenodeinthegraphofdependencies*/fromCellToGraphNode:function(col,row){returncol+row*this.spreadsheetWidth;},/***Retrievesthe<TD>elementbasedonthecellnotation(A1,C5,etc)*@paramcellStrastringrepresentingthecellnotation*@returnthe<TD>object*/getCellByCellNotation:function(cellStr){varcellCoords=this.fromCellNotationToArr(cellStr);returnthis.getCell(cellCoords.col,cellCoords.row);},/***Returnstherowforacellinthespreadsheetgivena<TD>element.NoteIEkeepstrackofTHelementsalso.*(ignoringcellheaders)*@paramtdElemthe<TD>element*@returntherowindex*/getCellRow:function(tdElem){returntdElem.parentNode.rowIndex-1;},/***Returnsthecolumn(withinthespreadsheet)foracellinthespreadsheetfora<TD>element(ignoringcellheaders)*@paramtdElemthe<TD>element*@returnthecolumnindex*/getCellCol:function(tdElem){returntdElem.cellIndex-1;},/***Returnsthe<TD>elementforagivencellinthespreadsheet.Forexample,getCell(0,0)shouldreturnthefirstcell*onthefirstrow(ignoringfirstcolumnandthethead).*@paramcolanumberrepresentingthecolofthecellinthespreadsheet.Startsfrom0(0beingtheequivalentofcolumnA).*@paramrowanumberrepresentingtherowofthecellinthespreadsheet.Startsfrom0(0beingtheequivalentofrow1).*@returna<TD>object*/getCell:function(col,row){if(dojo.isIE){returnthis.rows[row].cells[col+1];}else{returnthis.rows[row].cells[col+1];}},/***Utilityfunctionfordebuggingthegraphformanuallycheckingthedependencies*@returnastringwiththeentiregraph*/debugGraph:function(){varstr=" ";for(vari=0;i<this.ssGraph[0].length;i++){str+=this.fromGraphNodeToCellNotation(i)+" ";}str+="\n";for(varr=0;r<this.ssGraph.length;r++){str+=this.fromGraphNodeToCellNotation(r)+": [";for(varc=0;c<this.ssGraph[r].length;c++){str+=" "+this.ssGraph[r][c]+",";}str+="]\n"}returnstr;},/***Returnsthenumberofquotationmarksignoringtheescapedone*@paramstrthestringtoolookforquotationinside*@paramstartanintegerrepresentingthepositiontostartlookingfor*@paramstopanintegerrepresentingthepositiontostoplookingfor*/getNumberOfQuotes:function(str,start,stop){varnumQuotes=0;for(vari=start;i<stop;i++){if(str.charAt(i)=='"'){if(numQuotes%2==1&&i>0&&str.charAt(i-1)=="\\"){if(i>1&&str.charAt(i-2)=="\\"){numQuotes++;}}else{numQuotes++;}}}returnnumQuotes;},/***Evaluatesaformulaforacell,andputstheresultbackinthecell*@cellthespreadsheetcellwhichhasamongstotherpropertiesaformulapropertywhichisa*Stringcontainingtheformula.Examplesofstringsare:*sum(e4:b6),sum(e2,b4,c5)+cos(3.14)*avg(1,2,3),etc*@evaluateiftrue,thecell's value will be evaluated again. If false, if the cell'stypehas*beendetectedanditsformulahasbeenanalyzed,returndirectlythevalue*@noDependenciesiftrue,dependenciesarenotre-evaluated*@returntheresultoftheformula*/evalFormula:function(_cell,evaluate,noDependencies){varcellNotation=this.fromArrToCellNotation(this.getCellCol(_cell),this.getCellRow(_cell));varformula=_cell.formula;varerrors=false;if(formula==""||typeof(formula)=="undefined"){return"";}//acell's value it'saformulaonlyifitstartswith"="if(!evaluate&&_cell.cellType!=this.CELL_TYPES.FORMULA){return_cell.formula;}varresult;varoriginalGraphNode=this.fromCellToGraphNode(this.getCellCol(_cell),this.getCellRow(_cell));if(trim(""+formula).charAt(0)!="="){//trytodetectatypeforthecell(date,string,number)vartmp=formula.toLowerCase();//checkifit's a datevar_val;if((_val=this.parseDateFormat1(tmp))!=null){_cell.cellType=this.CELL_TYPES.DATE;}elseif((_val=this.parseDateFormat2(tmp))!=null){_cell.cellType=this.CELL_TYPES.DATE;}elseif((_val=this.parseNumberFormat1(tmp))!=null){//checkifit's a number_cell.cellType=this.CELL_TYPES.NUMBER;}else{//ifnoneoftheabove,consideritastring_val=formula;_cell.cellType=this.CELL_TYPES.STRING;}_cell.formula=_val;result=_val;}else{_cell.cellType=this.CELL_TYPES.FORMULA;this.debug("STEP 1: transform intervals of cells for "+cellNotation+": "+_cell.formula);/********************************************************************STEP1:transformintervalsofcellstoarrayofcells(B2:C3=>B2,B3,C2,C3*********************************************************************/varpcs=formula.match(this.reInterval);varinlinedFormula=formula;if(pcs!=null){//foreachinterval//TODOcheckthecellsisnotpartofastringfor(vari=0;i<pcs.length;i++){varcells=pcs[i].split(":");varcell0=this.fromCellNotationToArr(cells[0]);varcell1=this.fromCellNotationToArr(cells[1]);//buildastringwithalltheintermediaryvaluesvarinlinedInterval="";for(varcolIdx=cell0.col;colIdx<=cell1.col;colIdx++){for(varrowIdx=cell0.row;rowIdx<=cell1.row;rowIdx++){inlinedInterval+=this.fromIdxToChar(colIdx)+(rowIdx+1)+",";}}//removethelastcommainlinedInterval=inlinedInterval.substring(0,inlinedInterval.length-1);//replacedintervalwithinlineformula//foreachoccofcells,replaceitwithinlinedIntervalvarcellsPos=0;while((cellsPos=inlinedFormula.indexOf(pcs[i],cellsPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellsPos);if(numQuotes%2==0){inlinedFormula=inlinedFormula.substring(0,cellsPos)+inlinedInterval+inlinedFormula.substring(cellsPos+pcs[i].length);}cellsPos+=pcs[i].length;}}}this.debug("STEP 2: search for cell notations and mark the graph for "+cellNotation+": "+inlinedFormula);/********************************************************************STEP2:searchforcellnotationsthatarenotinsidestringsandmarkthegraph*********************************************************************///resetthegraphdependenciesforthiscellfor(vargrIdx=0;grIdx<this.spreadsheetWidth*this.spreadsheetHeight;grIdx++){this.ssGraph[originalGraphNode][grIdx]=0;}varcellsMatches=inlinedFormula.match(this.reCell);if(cellsMatches!=null){//foreachcellfor(vari=0;i<cellsMatches.length;i++){varcell=cellsMatches[i].substring(1);//markedgesingraphonlyforcellsthatarenotinsidestringsvarcellPos=0;while((cellPos=inlinedFormula.indexOf(cell,cellPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellPos);if(numQuotes%2==0){//marktheedgesinthegraphvarcellCoords=this.fromCellNotationToArr(cell);vargraphNode=this.fromCellToGraphNode(cellCoords.col,cellCoords.row);//alert("dependency : "+cellNotation+" "+this.fromArrToCellNotation(cellCoords.col,cellCoords.row));this.ssGraph[originalGraphNode][graphNode]=1;}cellPos+=cell.length;}}}try{this.debug("STEP 3: check circularities for "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP3:checkcircularities*********************************************************************/this.checkCircularitiesFromNode(originalGraphNode);this.debug("STEP 4: evaluate each cell's value for "+cellNotation);/********************************************************************STEP4:ifnocircularities,replaceeachcellnamewithitsvalue*********************************************************************/varcells=inlinedFormula.match(this.reCell);if(cells!=null){//foreachcell//TODOcheckthecellsisnotpartofastringfor(vari=0;i<cells.length;i++){varcell=cells[i].substring(1);//replacedcellwithit.lengtsvaluevarcellPos=0;while((cellPos=inlinedFormula.indexOf(cell,cellPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,cellPos);if(numQuotes%2==0){varcellValue;varcellObj=this.getCellByCellNotation(cell);try{cellValue=this.evalFormula(cellObj,false,true);}catch(e){throwe;}//forstrings,thevaluetoreplacehastocontainthequotesvartoReplace="";if(cellObj.cellType==this.CELL_TYPES.NUMBER){toReplace=cellValue;}if(cellObj.cellType==this.CELL_TYPES.STRING){toReplace="\""+cellValue+"\"";}if(cellObj.cellType==this.CELL_TYPES.FORMULA){toReplace=cellValue;}//ifcellhasnovalue,removeprevious,ifexistsorifpreviouscharis(removenext,//makesurethecellthathavenovaluedon't affect the formula by leaving random commasif(toReplace==""){vartmp=trim(inlinedFormula.substring(0,cellPos));vartmp2=trim(inlinedFormula.substring(cellPos+cell.length));//twocases:commaisbeforeandafterif(cellPos>0&&tmp.charAt(tmp.length-1)==','){inlinedFormula=inlinedFormula.substring(0,cellPos-1)+toReplace+inlinedFormula.substring(cellPos+cell.length);}else{if(cellPos>0&&tmp.charAt(tmp.length-1)=='('&&cellPos<inlinedFormula.length-1&&tmp2.charAt(0)==','){inlinedFormula=tmp+toReplace+tmp2.substring(1);}}}else{inlinedFormula=inlinedFormula.substring(0,cellPos)+toReplace+inlinedFormula.substring(cellPos+cell.length);}}cellPos+=cell.length;}}}this.debug("STEP 5: turn functions to lower case for "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP5:turnfunctiontolowercase*********************************************************************/varfunctions=inlinedFormula.match(this.reFunction);if(functions!=null){//foreachfnfor(vari=0;i<functions.length;i++){varfnToLower=functions[i].toLowerCase();//onlyifit's not lower alreadyif(fnToLower!=functions[i]){varfnPos=0;while((fnPos=inlinedFormula.indexOf(functions[i],fnPos))!=-1){//checkthenumberof" chars before pcs[i]varnumQuotes=this.getNumberOfQuotes(inlinedFormula,0,fnPos);if(numQuotes%2==0){inlinedFormula=inlinedFormula.substring(0,fnPos)+fnToLower+inlinedFormula.substring(fnPos+functions[i].length);}fnPos+=functions[i].length;}}}}//andnowevaluatetheformularesult=eval(inlinedFormula.substring(1));this.debug("result formula for "+cellNotation+", formula: "+inlinedFormula);}catch(e){this.debug(e);//throw(e);result=e;errors=true;}}if(!errors){if(!noDependencies){this.debug("STEP 6: re-evaluate cells dependent on this very cell: "+cellNotation+", formula: "+inlinedFormula);/********************************************************************STEP6:reevaluatedependentcells*********************************************************************/this.reevalDependentCells(originalGraphNode);}else{this.debug("STEP 6: dependencies will NOT be re-evaluated for cell: "+cellNotation);}}_cell.firstChild.innerHTML=result;this.debug("Final result for "+cellNotation+": "+result);returnresult;//returnthis.formatCellForPresentation(cell);;},/***Firesanevent*@paramevttheeventtobefired*/_fireEvent:function(evt){if(typeofthis[evt]=="function"){varargs=[this];for(vari=1;i<arguments.length;i++){args.push(arguments[i]);}this[evt].apply(this,args);}},/***Formatsthecellforpresentation.Theformattingshouldbebasedoncell's type (number, date, string) and cell's*format.Possibleformatsfordateare"MM/DD/YYYY","DD-MMM-YYYY",etc.*Currentlycell's formats are not supported yet.*@paramcellthe<TD>elementtobeformattedforpresentation*@returntheformattedvalue*/formatCellForPresentation:function(cell){varformula=cell.formula;if(formula&&typeof(formula)!="undefined"&&formula!=null){//now,thecellformatshouldbechecked...if(formulainstanceofDate){with(formula){returngetDate()+"-"+this.months[getMonth()].toUpperCase()+"-"+getFullYear();}}//now,thecellformatshouldbechecked...if(typeof(formula)=="number"){returnformula;}}},/***Createsadatefromastringparsingformat1:MM/DD/YYYY*@paramstrthestringtobeparsed*@returnaDateobjectifparsingsucceededornullifstringcouldnotbeparsed*/parseDateFormat1:function(str){var_date=str.match(this.reDate1);if(_date&&_date!=null){_date=""+_date;if(_date==trim(str)){varvals=_date.split("/");varmonth=parseInt(vals[0]);varday=parseInt(vals[1]);varyear=parseInt(vals[2]);if(this.isDateValid(day,month,year)){if(year<100&&year>=30){year=2000+year;}elseif(year<100){year=1900+year;}vardateObj=newDate();dateObj.setFullYear(year);dateObj.setMonth(month-1);dateObj.setUTCDate(day);returndateObj;}}}returnnull;},/***Createsadatefromastringparsingformat2:DD-MMM-YYYY*@paramstrthestringtobeparsed*@returnaDateobjectifparsingsucceededornullifstringcouldnotbeparsed*/parseDateFormat2:function(str){var_date=str.match(this.reDate2);if(_date&&_date!=null){_date=""+_date;if(_date==trim(str)){varvals=_date.split("-");varmonth=vals[1];varfound=-1;for(vari=0;i<this.months.length;i++){if(this.months[i]==month){found=i;break;}}if(found==-1){returnnull;}varday=parseInt(vals[0]);varyear=parseInt(vals[2]);if(this.isDateValid(day,month,year)){if(year<100&&year>=30){year=2000+year;}elseif(year<100){year=1900+year;}vardateObj=newDate();dateObj.setFullYear(year);dateObj.setMonth(found);dateObj.setUTCDate(day);returndateObj;}}}returnnull;},/***Createsanumberfromastring*@paramstrthestringtobeparsed*@returnanintorafloatifparsingsucceededornullifstringcouldnotbeparsed*/parseNumberFormat1:function(str){var_num=str.match(this.reNumber1);if(_num&&_num!=null){returnnull;}vardotIdx=str.indexOf(".");if(dotIdx!=-1&&dotIdx!=str.lastIndexOf(".")){returnnull;}vareIdx=str.indexOf("e");if(eIdx!=-1&&eIdx!=str.lastIndexOf("e")){returnnull;}if(dotIdx!=-1&&eIdx!=-1&&dotIdx+1!=eIdx){returnnull;}var_int=parseInt(str);if(""+_int==str){return_int;}var_float=parseFloat(str);if(!isNaN(_float)){return_float;}returnnull;},/***Validatesadate.Notimplementedyet-justasimplechecktherangesforeachparamaregood*@paramday*@parammonth*@paramyear*/isDateValid:function(day,month,year){if(month<1&&month>12&&day<1&&day>31){returnfalse;}//TODOcheckvaliddatereturntrue;},/***Spreadsheetspecificdebugfunction*@parammsgastringrepresentingthemessagetodebug*/debug:function(msg){vardate=newDate();vartmp=date.getHours()+":"+date.getMinutes()+"-"+date.getSeconds()+":"+date.getMilliseconds()+" : "+msg;vardbg=document.getElementById("debugDiv");dbg.value=tmp+"\n"+dbg.value;console.debug(tmp);},/***Adds"px"toanumber*@paramnumthenumber*/toPx:function(num){returnnum+"px";}}
);
/**************
MATHEMATICAL FUNCTIONS ***************/
function sum() {
var _sum = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_sum += arguments[i];
}
}
return _sum;
}
function avg() {
var _avg = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_avg += arguments[i];
}
_avg /= arguments.length;
}
return _avg;
}
function min() {
var _min = Number.POSITIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_min > arguments[i]) {
_min = arguments[i];
}
}
}
return _min;
}
function max() {
var _max = Number.NEGATIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_max < arguments[i]) {
_max = arguments[i];
}
}
}
return _max;
}
function product() {
var _product = 1;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_product *= arguments[i];
}
}
return _product;
}
var abs = Math.abs;
var acos = Math.acos;
var asin = Math.asin;
var atan = Math.atan;
var atan2 = Math.atan2;
var ceil = Math.ceil;
var cos = Math.cos;
var exp = Math.exp;
var floor = Math.floor;
var log = Math.log;
var pow = Math.pow;
var random = Math.random;
var round = Math.round;
var sin = Math.sin;
var sqrt = Math.sqrt;
var tan = Math.tan;
/**************
TEXT FUNCTIONS ***************/
function len() {
if(arguments != null && arguments.length > 0) {
return arguments[0].length;
}
}
/**
*/
dojo.provide("dojox.widget.iSpread");
dojo.provide("dojox.widget.iSpreadSheet");
dojo.require("dojo.string");
dojo.require("dojo.colors");
dojo.require("dijit._Widget");
dojo.require("dijit.ColorPalette");
dojo.require("dijit.Toolbar");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ToggleButton");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.ColorPalette");
dojo.require("dijit.form.Select");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit._editor.range");
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number].toString()
: match
;
});
};
dojo.declare(
"dojox.widget.iSpread",
dijit._Widget,
{
templateCssPath: dojo.moduleUrl("dojox.widget", "ispread/templates/common.css"),
tc: null,
tabContainer: null,
tabs: [],
activeTab: null,
boldItem: null,
italicItem: null,
underlineItem: null,
colorItem: null,
bgcolorItem: null,
fontMenu: null,
fontSizeMenu: null,
rowsMenu: null,
colsMenu: null,
sheetMenu: null,
functionsMenu: null,
iconMap: { justifyleft:"justifyleft",
justifycenter:"justifycenter",
justifyright:"justifyright",
justifyfull:"justifyfull",
bold:"bold",
italic:"italic",
underline: "underline",
forecolor:"forecolor",
backcolor:"backcolor"},
);
// dojo.widget.defineWidget(
dojo.declare(
"dojox.widget.iSpreadSheet",
dijit._Widget,
{
CELL_TYPES: { NUMBER:0, STRING:1, DATE:2, FORMULA:3 },
FORMATTING_TYPES: { FONT:0, FONT_SIZE:1, COLOR:2, BG_COLOR:3, BOLD:4, ITALIC:5, UNDERLINE:6, ALIGN:7 },
FORMULAS: { SUM:0, AVG:0 },
//serif', 'sans-serif', 'cursive', 'fantasy', and 'monospace
MINIMUM_CELL_WIDTH: 12,
MINIMUM_CELL_HEIGHT: 12,
currentFocusedCol : 0,
currentFocusedRow : 0,
tbody: null,
rows: null,
SELECTION_MODES: { RECTANGLE:0, RANDOM:1 },
selectionMode: 0,
// properties for cell selection
isSelectingCells: false,
selectionStartCell: null,
lastSelectedRegion : null,
// properties for column selection
isSelectingColumns: false,
selectionStartColumn: null,
lastSelectedColumns: [],
// properties for row selection
isSelectingRows: false,
selectionStartRow: null,
lastSelectedRows: [],
// properties needed for horizontal resizing of columns
isResizingHorizontal: false,
resizeOrigXPos: 0,
resizeOrigTH: null,
// properties needed for vertical resizing of rows
isResizingVertical: false,
resizeOrigYPos: 0,
resizeOrigTD: null,
// properties for editing
isEditing: false,
inputElem: null,
spreadsheetWidth: 0,
spreadsheetHeight: 0,
isChrome: false,
isIE: false,
);
/**************
***************/
function sum() {
var _sum = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_sum += arguments[i];
}
}
return _sum;
}
function avg() {
var _avg = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_avg += arguments[i];
}
_avg /= arguments.length;
}
return _avg;
}
function min() {
var _min = Number.POSITIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_min > arguments[i]) {
_min = arguments[i];
}
}
}
return _min;
}
function max() {
var _max = Number.NEGATIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_max < arguments[i]) {
_max = arguments[i];
}
}
}
return _max;
}
function count() {
var _count = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(arguments[i] != null && typeof(arguments[i]) != "undefined" && arguments[i] != "") {
_count ++;
}
}
}
}
function product() {
var _product = 1;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_product *= arguments[i];
}
}
}
var abs = Math.abs;
var acos = Math.acos;
var asin = Math.asin;
var atan = Math.atan;
var atan2 = Math.atan2;
var ceil = Math.ceil;
var cos = Math.cos;
var exp = Math.exp;
var floor = Math.floor;
var log = Math.log;
var pow = Math.pow;
var random = Math.random;
var round = Math.round;
var sin = Math.sin;
var sqrt = Math.sqrt;
var tan = Math.tan;
/**************
***************/
function len() {
if(arguments != null && arguments.length > 0) {
return arguments[0].length;
}
}
function lower() {
if(arguments != null && arguments.length > 0) {
return arguments[0].toLowerCase();
}
}
function upper() {
if(arguments != null && arguments.length > 0) {
return arguments[0].toUpperCase();
}
}
function left() {
if(arguments != null && arguments.length > 0) {
var endPos = 1;
if(arguments[1]) {
endPos = arguments[1];
}
return arguments[0].substring(0, endPos);
}
}
function right() {
if(arguments != null && arguments.length > 0) {
var startPos = 1;
if(arguments[1]) {
startPos = arguments[1];
}
return arguments[0].substring(arguments[0].length - startPos);
}
}
var trim = dojo.trim;
/**
*/
dojo.provide("dojox.widget.iSpread");
dojo.provide("dojox.widget.iSpreadSheet");
dojo.require("dojo.string");
dojo.require("dojo.colors");
dojo.require("dijit._Widget");
dojo.require("dijit.ColorPalette");
dojo.require("dijit.Toolbar");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ToggleButton");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.ColorPalette");
dojo.require("dijit.form.Select");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit._editor.range");
dojo.declare(
"dojox.widget.iSpread",
dijit._Widget,
{
templateCssPath: dojo.moduleUrl("dojox.widget", "ispread/templates/common.css"),
tc: null,
tabContainer: null,
tabs: [],
activeTab: null,
boldItem: null,
italicItem: null,
underlineItem: null,
colorItem: null,
bgcolorItem: null,
fontMenu: null,
fontSizeMenu: null,
rowsMenu: null,
colsMenu: null,
sheetMenu: null,
functionsMenu: null,
iconMap: { justifyleft:"justifyleft",
justifycenter:"justifycenter",
justifyright:"justifyright",
justifyfull:"justifyfull",
bold:"bold",
italic:"italic",
underline: "underline",
forecolor:"forecolor",
backcolor:"backcolor"},
);
// dojo.widget.defineWidget(
dojo.declare(
"dojox.widget.iSpreadSheet",
dijit._Widget,
{
CELL_TYPES: { NUMBER:0, STRING:1, DATE:2, FORMULA:3 },
FORMATTING_TYPES: { FONT:0, FONT_SIZE:1, COLOR:2, BG_COLOR:3, BOLD:4, ITALIC:5, UNDERLINE:6, ALIGN:7 },
FORMULAS: { SUM:0, AVG:0 },
//serif', 'sans-serif', 'cursive', 'fantasy', and 'monospace
MINIMUM_CELL_WIDTH: 12,
MINIMUM_CELL_HEIGHT: 12,
currentFocusedCol : 0,
currentFocusedRow : 0,
tbody: null,
rows: null,
SELECTION_MODES: { RECTANGLE:0, RANDOM:1 },
selectionMode: 0,
// properties for cell selection
isSelectingCells: false,
selectionStartCell: null,
lastSelectedRegion : null,
// properties for column selection
isSelectingColumns: false,
selectionStartColumn: null,
lastSelectedColumns: [],
// properties for row selection
isSelectingRows: false,
selectionStartRow: null,
lastSelectedRows: [],
// properties needed for horizontal resizing of columns
isResizingHorizontal: false,
resizeOrigXPos: 0,
resizeOrigTH: null,
// properties needed for vertical resizing of rows
isResizingVertical: false,
resizeOrigYPos: 0,
resizeOrigTD: null,
// properties for editing
isEditing: false,
inputElem: null,
spreadsheetWidth: 0,
spreadsheetHeight: 0,
isChrome: false,
isIE: false,
);
/**************
***************/
function sum() {
var _sum = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_sum += arguments[i];
}
}
return _sum;
}
function avg() {
var _avg = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_avg += arguments[i];
}
_avg /= arguments.length;
}
return _avg;
}
function min() {
var _min = Number.POSITIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_min > arguments[i]) {
_min = arguments[i];
}
}
}
return _min;
}
function max() {
var _max = Number.NEGATIVE_INFINITY;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(_max < arguments[i]) {
_max = arguments[i];
}
}
}
return _max;
}
function count() {
var _count = 0;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
if(arguments[i] != null && typeof(arguments[i]) != "undefined" && arguments[i] != "") {
_count ++;
}
}
}
}
function product() {
var _product = 1;
if(arguments != null && arguments.length > 0) {
for(var i = 0; i < arguments.length; i++) {
_product *= arguments[i];
}
}
}
var abs = Math.abs;
var acos = Math.acos;
var asin = Math.asin;
var atan = Math.atan;
var atan2 = Math.atan2;
var ceil = Math.ceil;
var cos = Math.cos;
var exp = Math.exp;
var floor = Math.floor;
var log = Math.log;
var pow = Math.pow;
var random = Math.random;
var round = Math.round;
var sin = Math.sin;
var sqrt = Math.sqrt;
var tan = Math.tan;
/**************
***************/
function len() {
if(arguments != null && arguments.length > 0) {
return arguments[0].length;
}
}
function lower() {
if(arguments != null && arguments.length > 0) {
return arguments[0].toLowerCase();
}
}
function upper() {
if(arguments != null && arguments.length > 0) {
return arguments[0].toUpperCase();
}
}
function left() {
if(arguments != null && arguments.length > 0) {
var endPos = 1;
if(arguments[1]) {
endPos = arguments[1];
}
return arguments[0].substring(0, endPos);
}
}
function right() {
if(arguments != null && arguments.length > 0) {
var startPos = 1;
if(arguments[1]) {
startPos = arguments[1];
}
return arguments[0].substring(arguments[0].length - startPos);
}
}
var trim = dojo.trim;