/*
 * yeroon.net/ggplot2:
 * A web interface for the R package ggplot2.
 * (c) 2010 Jeroen Ooms
 * http://www.jeroenooms.com'
 */
Ext.onReady(function(){var w;var af;var V;var R;var c="/R";function aa(ag){this.geom=ag;if(ag=="bar"){this.stat="set_identity"}}function W(ag,al,aj,ai,ah,ak){this.x=ag;this.y=al;this.group=aj;this.colour=ai;this.weight=ah;this.facet=new Object();this.layers=new Object()}W.prototype.set=function(ag,ai,ah){if(ah==null){if(ai=="default"){delete this[ag]}else{this[ag]=ai}}else{if(ah=="facet"){if(ai=="default"){delete this.facet[ag]}else{this.facet[ag]=ai}}else{if(ai=="default"){delete this.layers[ah][ag]}else{this.layers[ah][ag]=ai}}}};W.prototype.addLayer=function(ag,ah){return this.layers[ah]=new aa(ag)};W.prototype.removeLayer=function(ag){delete this.layers[ag]};W.prototype.toJSON=function(){return Ext.util.JSON.encode(this)};W.prototype.toString=function(){return Ext.util.JSON.encode(this)};function g(ah,aj,ag,ai){if(ai){myMask=new Ext.LoadMask(ai,{msg:"Please wait..."});myMask.show()}else{myMask=null}Ext.Ajax.request({timeout:60000,url:c+"/"+ah,method:"POST",mask:myMask,inputList:aj,params:{inputList:Ext.util.JSON.encode(aj)},success:function(am,al){if(al.mask!=null){al.mask.hide()}try{result=Ext.decode(am.responseText)}catch(ak){alert("error in decoding json response:\n\n"+am.responseText)}finally{if(!result){return false}if(result.success){ag(result,al)}else{alert("R returned an error:\n\n"+result.error)}}},failure:function(ak,al){if(al.mask!=null){al.mask.hide()}alert("server-side failure: HTTP"+ak.status)}})}function ac(ai){syntax="ggplot(myData, aes(";var ag=true;for(z in ai){if(typeof(ai[z])=="string"&&z!="facet"){if(!ag){syntax=syntax+", "}syntax=syntax+z+"="+ai[z].substring(4);ag=false}}syntax=syntax+"))";layers=ai.layers;var ak=true;for(everyLayer in layers){ak=false;var aj=layers[everyLayer];var ah=new Array();var al=new Array();for(z in aj){if(typeof(aj[z])=="string"&&aj[z].substring(0,3)=="set"){thisValue=aj[z].substring(4);if(thisValue=="FALSE"||thisValue=="TRUE"){ah.push(z+"="+aj[z].substring(4))}else{if(w.Aesthetics[z].type=="numeric"){ah.push(z+"="+aj[z].substring(4))}else{ah.push(z+'="'+aj[z].substring(4)+'"')}}}if(typeof(aj[z])=="string"&&aj[z].substring(0,3)=="map"){al.push(z+"="+aj[z].substring(4))}}syntax=syntax+" + geom_"+aj.geom+"("+ah.join(",");if(al.length>0){if(ah.length>0){syntax=syntax+", "}syntax=syntax+"aes("+al.join(",")+")"}syntax=syntax+")"}if(ak&&ai.y!=undefined){if(ai.y.substring(4)=="..density.."||ai.y.substring(4)=="..count.."){syntax=syntax+' + geom_blank(stat="bin")'}else{syntax=syntax+" + geom_blank()"}}if(ai.facet.map){syntax=syntax+" + facet_wrap(~"+ai.facet.map.substring(4);if(ai.facet.nrow){syntax=syntax+", nrow = "+ai.facet.nrow.substring(4)}if(ai.facet.scales){syntax=syntax+', scales = "'+ai.facet.scales.substring(4)+'"'}syntax=syntax+")"}return(syntax)}function N(){var ag=document.getElementById("historyCmp");ag.scrollTop=ag.scrollHeight}function m(ag){try{return Ext.util.JSON.decode(ag)}catch(ah){return false}}function Q(ag){myP=document.createElement("p");myP.appendChild(document.createTextNode(ag));Ext.get("historyCmp").appendChild(myP);N()}function b(ag){Ext.DomHelper.overwrite("syntaxdiv","<pre><code> > "+ag+"<img id='cursor' src='images/cursor2.gif' /></code></pre>")}function K(){var ag=Ext.getCmp("workspace").plotConfig.dataFile;Ext.getCmp("workspace").plotConfig=new W();Ext.getCmp("workspace").plotConfig.dataFile=ag;Ext.getCmp("layerList").getStore().removeAll();Ext.getCmp("workspace").load({url:"emptyfile.txt",method:"GET"});t(Ext.getCmp("workspace").plotConfig);G(null);Ext.getCmp("plotMenu").removeAll();geomMenu=O(w);v()}function ae(ai){for(var ag in ai.layers){thisLayer=ai.layers[ag];thisGeom=thisLayer.geom;if(w.Required[thisGeom]){requirements=w.Required[thisGeom];for(var ah=0;ah<requirements.length;ah++){thisReq=requirements[ah];if(!thisLayer[thisReq]){alert("Aesthetic '"+thisReq+"' is required for 'geom_"+thisGeom+"'. Please set/map it in it's menu, and try again.");return false}}}}return true}function F(){plotConfig=Ext.getCmp("workspace").plotConfig;if(plotConfig.x==null||plotConfig.y==null){alert("You need to set X and Y first!")}else{if(ae(plotConfig)){width=Ext.getCmp("workspace").getSize().width;height=Ext.getCmp("workspace").getSize().height;plotConfig.width=width;plotConfig.height=height-40;Ext.getCmp("drawButton").disable();Ext.getCmp("pdfbutton").disable();Ext.getCmp("svgbutton").disable();Q(ac(plotConfig)+";");Ext.getCmp("workspace").load({timeout:60,url:c+"/ggplot-png",method:"POST",params:{plotRequest:plotConfig.toJSON()},callback:function(ah,ai,ag){Ext.getCmp("drawButton").enable();Ext.getCmp("pdfbutton").enable();Ext.getCmp("svgbutton").enable();plotResult=m(ag.responseText);if(plotResult&&!plotResult.success){Q("Error: "+plotResult.error)}}})}}}function ad(){plotConfig=Ext.getCmp("workspace").plotConfig;if(plotConfig.x==null||plotConfig.y==null){alert("You need to set X and Y first!")}else{myWindow=window.open();myWindow.document.write("PDF link will appear here... please wait (don't close this window)\n\n");Ext.getCmp("pdfbutton").disable();Ext.Ajax.request({timeout:60000,url:c+"/ggplot-pdf",method:"POST",params:{plotRequest:plotConfig.toJSON()},success:function(ah){try{result=Ext.decode(ah.responseText)}catch(ag){alert("error in decoding data: "+ah.responseText)}finally{Ext.getCmp("pdfbutton").enable();if(result.success){myWindow.document.write(('<a href="plots/'+result.pdfurl+'">click here to get pdf </a>'))}else{alert("R returned an error:\n\n"+result.error)}}},failure:function(){Ext.getCmp("pdfbutton").enable()}})}}function S(){plotConfig=Ext.getCmp("workspace").plotConfig;if(plotConfig.x==null||plotConfig.y==null){alert("You need to set X and Y first!")}else{myWindow=window.open();myWindow.document.write("svg link will appear here... please wait (don't close this window)\n\n");Ext.getCmp("svgbutton").disable();Ext.Ajax.request({timeout:60000,url:c+"/ggplot-svg",method:"POST",params:{plotRequest:plotConfig.toJSON()},success:function(ah){try{result=Ext.decode(ah.responseText)}catch(ag){alert("error in decoding data: "+ah.responseText)}finally{Ext.getCmp("svgbutton").enable();if(result.success){myWindow.document.write(('<a href="plots/'+result.svgurl+'">click here to get svg </a>'))}else{alert("R returned an error:\n\n"+result.error)}}},failure:function(){Ext.getCmp("svgbutton").enable()}})}}function G(ag){htmlString="<h1> Layer Config:</h1>";for(prop in ag){htmlString=htmlString+"<p>"+prop+": "+ag[prop]+"</p>"}document.getElementById("detailDiv").innerHTML=htmlString;Ext.get("detailDiv").hide().slideIn("t",{stopFx:true,duration:0.2});b(ac(Ext.getCmp("workspace").plotConfig))}function t(ag){htmlString="<h1> Global Options:</h1>";if(ag.x){htmlString=htmlString+"<p> x: "+ag.x+"</p>"}else{htmlString=htmlString+"<p> <span class='invalid'> x: undefined </span></p>"}if(ag.y){htmlString=htmlString+"<p> y: "+ag.y+"</p>"}else{htmlString=htmlString+"<p><span class='invalid'> y: undefined </span></p>"}if(ag.weight){htmlString=htmlString+"<p> weight: "+ag.weight+"</p>"}if(ag.group){htmlString=htmlString+"<p> group: "+ag.group+"</p>"}if(ag.colour){htmlString=htmlString+"<p> colour: "+ag.colour+"</p>"}if(ag.facet.map){htmlString=htmlString+"<p> facet: "+ag.facet.map+"</p>"}numberOfLayers=Ext.getCmp("layerList").getStore().getCount();if(numberOfLayers>0){htmlString=htmlString+"<p> layers: "+Ext.getCmp("layerList").getStore().getCount()+"</p>"}else{htmlString=htmlString+"<p><span class='invalid'>  layers: 0 </span></p>"}document.getElementById("generalDetailDiv").innerHTML=htmlString;Ext.get("generalDetailDiv").hide().slideIn("l",{stopFx:true,duration:0.2});b(ac(ag))}function f(ai,ah,ag){plotConfig=Ext.getCmp("workspace").plotConfig;G(plotConfig.layers[ag.id])}function d(ag,ai,ah){dataVariables=Ext.getCmp("workspace").dataVariables;thisLayerMenu=new Ext.menu.Item({id:ah,text:"Layer: "+ag,iconCls:"icon_"+ag,handler:function(){return false},menu:{items:['<b class="menu-title">Layer: '+ag+"</b>"]}});for(thisaes=0;thisaes<ai.length;thisaes++){myAes=ai[thisaes];myValues=w.Aesthetics[myAes].values;mapSetMenu=thisLayerMenu.menu.add({text:myAes,handler:function(){return false},iconCls:"icon_prop",key:myAes,menu:{}});if(w.Aesthetics[myAes].set){mapSetMenu.menu.add({text:"Set",iconCls:"icon_set",handler:function(){return false},menu:e(myAes,myValues,"default",!w.Aesthetics[myAes].required,ah,"set_",w.Aesthetics[myAes].custom)})}newDataVariables=dataVariables;if(w.Statvar[ag]){newDataVariables=w.Statvar[ag].concat("-").concat(newDataVariables)}if(w.Aesthetics[myAes].map){mapSetMenu.menu.add({iconCls:"icon_map",text:"Map",handler:function(){return false},menu:e(myAes,newDataVariables,"default",!w.Aesthetics[myAes].set,ah,"map_",false)})}}thisLayerMenu.menu.add("-");thisLayerMenu.menu.add({text:"Remove Layer",iconCls:"delete",handler:function(){plotConfig.removeLayer(ah);Ext.getCmp("plotMenu").remove(ah);n(ah);G(null);t(Ext.getCmp("workspace").plotConfig)}});return thisLayerMenu}function P(ag,ah){Ext.getCmp("layerList").getStore().loadData([[ah,ag]],true);activeRecord=Ext.getCmp("layerList").getStore().getById(ah);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord]);return activeRecord}function n(ag){thisRecord=Ext.getCmp("layerList").getStore().getById(ag);Ext.getCmp("layerList").getStore().remove(thisRecord);Ext.getCmp("layerList").getStore().refreshData()}function h(ag,ah){plotConfig=Ext.getCmp("workspace").plotConfig;var ai="layer"+(Math.floor(Math.random()*90000)+10000);plotConfig.addLayer(ag,ai);newMenu=d(ag,ah,ai);newRecord=P(ag,ai);newRecord.layerMenu=newMenu;t(Ext.getCmp("workspace").plotConfig);Ext.getCmp("layerList").getSelectionModel().on("rowselect",f)}var y=new Ext.menu.Menu({id:"plotMenu",items:[],handler:function(){return false}});function e(an,ao,ai,am,al,ak,ah){if(an=="y"){ao=new Array("..count..","..density..","-").concat(ao)}plotConfig=Ext.getCmp("workspace").plotConfig;var aj=new Ext.menu.Menu({items:[]});if(am){myDefault=aj.add({text:"default",key:an,value:"default",layer:al,group:al+an,checked:ai=="default",handler:function(){plotConfig.set(this.key,this.value,this.layer);if((this.key=="colour"||this.key=="fill")&&this.layer!=null){this.myCP.unselect(false)}if(this.layer!=null&&this.layer!="facet"){activeRecord=Ext.getCmp("layerList").getStore().getById(this.layer);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord])}else{t(plotConfig)}}});aj.add("-")}var ag;if((an=="colour"||an=="fill")&ak=="set_"){aj.add(ag=myDefault.myCP=new Ext.ColorPalette({layer:al,key:an,handler:function(ap,aq){this.customChoise.enable();this.customChoise.value="set_#"+aq;this.customChoise.setText("custom: #"+aq);this.customChoise.setChecked(true);plotConfig.set(this.key,"set_#"+aq,this.customChoise.layer);activeRecord=Ext.getCmp("layerList").getStore().getById(this.layer);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord]);Ext.getCmp("plotMenu").hide();this.customChoise.getEl().highlight(aq)}}))}for(thisVal=0;thisVal<ao.length;thisVal++){if(ao[thisVal]=="-"){aj.add("-")}else{aj.add({text:ao[thisVal],key:an,value:ak+ao[thisVal],layer:al,group:al+an,checked:ao[thisVal]==ai,handler:function(){plotConfig.set(this.key,this.value,this.layer);if(this.key=="y"){if(this.value.substring(4)=="..count.."||this.value.substring(4)=="..density.."){Ext.getCmp("addLayerMenu1").enable();Ext.getCmp("addLayerMenu2").disable();Ext.getCmp("addLayerMenu3").disable()}else{Ext.getCmp("addLayerMenu1").disable();Ext.getCmp("addLayerMenu2").enable();Ext.getCmp("addLayerMenu3").enable()}}if(this.layer!=null&&this.layer!="facet"){activeRecord=Ext.getCmp("layerList").getStore().getById(this.layer);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord])}else{t(plotConfig)}}})}}if(ah){aj.add("-");customChoise=aj.add({text:"custom: (no value set)",key:an,disabled:true,value:"default",layer:al,myCP:ag,group:al+an,checked:false,handler:function(){plotConfig.set(this.key,this.value,this.layer);activeRecord=Ext.getCmp("layerList").getStore().getById(this.layer);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord])},listeners:{checkchange:function(aq,ap){if(!ap){if(this.key=="colour"||this.key=="fill"){this.myCP.unselect(false)}this.setText("custom: (no value set)");this.disable()}}}});if(an=="colour"||an=="fill"){ag.customChoise=customChoise}thisField=aj.add({xtype:"buttongroup",autoWidth:true,columns:2,defaults:{iconAlign:"left"},items:[]});if(w.Aesthetics[an].type=="numeric"){customValueField=thisField.add({xtype:"numberfield",allowBlank:false,validateOnBlur:false,text:"custom value"})}else{customValueField=thisField.add({xtype:"textfield",allowBlank:false,validateOnBlur:false,text:"custom value"})}thisField.add({customChoise:customChoise,myCP:ag,key:an,layer:al,varMenu:aj,customValueField:customValueField,text:"set value",handler:function(){if(!this.customValueField.validate()){return false}if(this.key=="colour"||this.key=="fill"){this.myCP.unselect(false)}var ap=this.customValueField.getValue();this.customChoise.enable();this.customChoise.value="set_"+ap;this.customChoise.setText("custom: "+ap);this.customChoise.getEl().highlight();this.customChoise.setChecked(true);if(this.customChoise.checked){plotConfig.set(this.customChoise.key,this.customChoise.value,this.customChoise.layer);activeRecord=Ext.getCmp("layerList").getStore().getById(this.layer);Ext.getCmp("layerList").getSelectionModel().selectRecords([activeRecord])}this.customValueField.reset()}})}return aj}function v(){dataVariables=Ext.getCmp("workspace").dataVariables;var ag=w.Defaults;for(i=0;i<ag.length;i++){if(ag[i]=="-"){Ext.getCmp("plotMenu").add("-")}else{if(ag[i].required){Ext.getCmp("plotMenu").add({id:"mapping"+ag[i].name,text:"Map "+ag[i].name+" (required)",iconCls:"icon_map",handler:function(){return false},menu:e(ag[i].name,Ext.util.JSON.decode(Ext.util.JSON.encode(dataVariables)),"default",false,null,"map_")})}else{Ext.getCmp("plotMenu").add({id:"mapping"+ag[i].name,text:"Map "+ag[i].name,iconCls:"icon_map",handler:function(){return false},menu:e(ag[i].name,Ext.util.JSON.decode(Ext.util.JSON.encode(dataVariables)),"default",true,null,"map_")})}}}facetMenu=Ext.getCmp("plotMenu").add({id:"facet",text:"Facet",iconCls:"icon_facet",handler:function(){return false},menu:{}});Ext.getCmp("plotMenu").add("-");facetProperties=w.Facet;for(thisaes=0;thisaes<facetProperties.length;thisaes++){thisProp=facetProperties[thisaes];if(thisProp.set){facetMenu.menu.add({text:thisProp.name,handler:function(){return false},iconCls:"icon_set",key:thisProp.name,menu:e(thisProp.name,thisProp.values,"default",true,"facet","set_")})}else{if(thisProp.map){facetMenu.menu.add({text:thisProp.name,handler:function(){return false},iconCls:"icon_map",key:thisProp.name,menu:e(thisProp.name,dataVariables,"default",true,"facet","map_")})}}}Ext.getCmp("plotMenu").add({text:"Add Layer",iconCls:"add",menu:Ext.getCmp("geomMenu"),handler:function(){return false}})}function p(){Ext.Ajax.request({url:"menuData.json",success:function(ah){try{w=Ext.decode(ah.responseText)}catch(ag){alert("error in decoding menuData.json")}finally{geomMenu=O(w)}},failure:function(){alert("menuData.json could not be loaded")}})}function O(ai){geomMenu=new Ext.menu.Menu({id:"geomMenu",items:['<b class="menu-title">Add New Layer</b>'],handler:function(){return false}});Ext.getCmp("geomMenu").add({id:"addLayerMenu1",text:"Univariate Geoms",iconCls:"add",handler:function(){return false},disabled:true,menu:{}});var ah=ai.Geoms1;for(i=0;i<ah.length;i++){Ext.getCmp("addLayerMenu1").menu.add({text:ah[i].geom,iconCls:"icon_"+ah[i].geom,geom:ah[i].geom,aes:ah[i].aes,values:ah[i].values,id:"geom_"+ah[i].geom,handler:function(){h(this.geom,this.aes)}})}Ext.getCmp("geomMenu").add({id:"addLayerMenu2",text:"Bivariate Geoms",iconCls:"add",handler:function(){return false},disabled:true,menu:{}});var ag=ai.Geoms2;for(i=0;i<ag.length;i++){Ext.getCmp("addLayerMenu2").menu.add({text:ag[i].geom,iconCls:"icon_"+ag[i].geom,geom:ag[i].geom,aes:ag[i].aes,values:ag[i].values,id:"geom_"+ag[i].geom,handler:function(){h(this.geom,this.aes)}})}Ext.getCmp("geomMenu").add({id:"addLayerMenu3",text:"fixed lines/bars",iconCls:"add",handler:function(){return false},disabled:true,menu:{}});var aj=ai.Geoms3;for(i=0;i<aj.length;i++){Ext.getCmp("addLayerMenu3").menu.add({text:aj[i].geom,iconCls:"icon_"+aj[i].geom,geom:aj[i].geom,aes:aj[i].aes,values:aj[i].values,id:"geom_"+aj[i].geom,handler:function(){h(this.geom,this.aes)}})}return af}imageContext=function(ah,ag,ai){plotConfig=Ext.getCmp("workspace").plotConfig;y.showAt(ah.getPoint());ah.stopEvent()};function a(ag){if(V){return}V=new Ext.Window({width:600,height:400,resizable:false,id:"uploadWindow",title:"Upload Data",border:false,items:[{xtype:"form",id:"uploadForm",autoHeight:true,autoWidth:true,frame:true,fileUpload:true,border:false,bodyStyle:"padding: 5px 10px 5px 10px;",labelWidth:60,defaults:{anchor:"100%"},items:[{xtype:"fileuploadfield",id:"fileuploadfield",name:"datafile",emptyText:"Upload any .csv, .txt, .xls, .sav, .dta ... ",listeners:{fileselected:q},fieldLabel:"Data File"},{xtype:"fieldset",title:"import options",collapsible:true,collapsed:true,forceLayout:true,layout:"column",listeners:{collapse:function(){Ext.getCmp("guessGrid").setHeight(253)},expand:function(){Ext.getCmp("guessGrid").setHeight(185)}},items:[{columnWidth:0.5,layout:"form",defaults:{xtype:"combo",mode:"local",editable:false,typeAhead:false,triggerAction:"all",labelWidth:100,disabled:true,anchor:"95%",listeners:{select:s}},items:[{fieldLabel:"Type",name:"type",id:"guessType",store:["csv","csv2","delim","delim2"]},{fieldLabel:"Header",id:"guessHeader",name:"header",store:[true,false]}]},{columnWidth:0.5,layout:"form",defaults:{xtype:"combo",mode:"local",editable:false,typeAhead:false,triggerAction:"all",labelWidth:100,disabled:true,anchor:"95%",listeners:{select:s}},items:[{fieldLabel:"Seperator",name:"sep",id:"guessSep",store:[[",",", (comma)"],[";","; (semicolon)"],["\t","\\t (tab)"],["",'"" (White Space)']]},{fieldLabel:"Decimal",id:"guessDec",name:"dec",store:[[".",". (dot)"],[",",", (comma)"]]}]}]},{xtype:"grid",enableHdMenu:false,draggable:false,enableColumnMove:false,id:"guessGrid",cls:"guessGrid",height:187,autoWidth:true,cm:new Ext.grid.ColumnModel({id:"dataCM"}),store:new Ext.data.ArrayStore({id:"dataStore"}),frame:false}]}],buttons:[{text:"Import",id:"importButton",disabled:true,handler:function(){k(this.tempDataFile)}}],listeners:{beforedestroy:function(){V=null}}});V.show(ag);Ext.getCmp("uploadForm").getForm().waitMsgTarget=Ext.getCmp("uploadWindow").getLayoutTarget()}function q(ah,ag){Ext.getCmp("importButton").disable();Ext.getCmp("uploadForm").getForm().submit({method:"post",url:c+"/uploadGuess",waitMsg:"Uploading data...",success:function(ai,aj){if(!aj.result){alert("Error in uploading data. Try a different server");return false}if(typeof(aj.result.output.variableNames)=="string"){aj.result.output.variableNames=new Array(aj.result.output.variableNames)}U(aj.result.output);Ext.getCmp("importButton").tempDataFile=aj.result.output.dataFile;Ext.getCmp("guessType").setValue(aj.result.output.guess.type);Ext.getCmp("guessHeader").setValue(aj.result.output.guess.header);Ext.getCmp("guessSep").setValue(aj.result.output.guess.sep);Ext.getCmp("guessDec").setValue(aj.result.output.guess.dec);dataType=aj.result.output.guess.type;if(dataType=="csv"|dataType=="csv2"|dataType=="delim"|dataType=="delim2"){Ext.getCmp("guessType").enable();Ext.getCmp("guessHeader").enable();Ext.getCmp("guessSep").enable();Ext.getCmp("guessDec").enable()}else{Ext.getCmp("guessType").disable();Ext.getCmp("guessHeader").disable();Ext.getCmp("guessSep").disable();Ext.getCmp("guessDec").disable()}if(dataType=="xls"){Ext.getCmp("guessHeader").enable()}if(aj.result.output.error){Ext.getCmp("importButton").disable();alert(aj.result.output.error)}else{Ext.getCmp("importButton").enable()}},failure:function(ai,aj){U({variableNames:[],variableData:[]});Ext.getCmp("importButton").disable();Ext.getCmp("guessType").disable();Ext.getCmp("guessHeader").disable();Ext.getCmp("guessSep").disable();Ext.getCmp("guessDec").disable();alert("R catched an error: "+aj.result.error)}})}function s(){dataType=Ext.getCmp("guessType").value;dataHeader=Ext.getCmp("guessHeader").value;dataSep=Ext.getCmp("guessSep").value;dataDec=Ext.getCmp("guessDec").value;dataFile=Ext.getCmp("importButton").tempDataFile;function ag(ah){if(typeof(ah.variableNames)=="string"){ah.variableNames=new Array(ah.variableNames)}U(ah);Ext.getCmp("guessType").setValue(ah.guess.type);Ext.getCmp("guessHeader").setValue(ah.guess.header);Ext.getCmp("guessSep").setValue(ah.guess.sep);Ext.getCmp("guessDec").setValue(ah.guess.dec);if(ah.error){Ext.getCmp("importButton").disable();alert(ah.error)}else{Ext.getCmp("importButton").enable()}if(ah.error){Ext.getCmp("importButton").disable();alert(o.result.output.error)}else{Ext.getCmp("importButton").enable()}}Ext.getCmp("importButton").disable();g("customImport",{dataType:dataType,dataHeader:dataHeader,dataSep:dataSep,dataDec:dataDec,dataFile:dataFile},ag,Ext.getCmp("uploadWindow").getLayoutTarget())}function k(ah){Ext.getCmp("importButton").disable();var ag=new Ext.LoadMask(Ext.getCmp("uploadWindow").getLayoutTarget(),{msg:"Please wait..."});ag.show();Ext.Ajax.request({timeout:60000,url:c+"/listVariables",method:"POST",params:{dataFile:ah},success:function(ak){ag.hide();Ext.getCmp("importButton").enable();try{varListing=Ext.decode(ak.responseText)}catch(ai){alert("error in decoding menuData.json")}finally{if(varListing&&!varListing.success){alert(varListing.error)}else{if(varListing&&varListing.success){variables=varListing.variables[0].children.concat(varListing.variables[1].children);dataVariables=new Array();for(thisV=0;thisV<variables.length;thisV++){dataVariables[thisV]=variables[thisV].text}Ext.getCmp("workspace").dataVariables=dataVariables;v();Ext.getCmp("resetbutton").enable();Ext.getCmp("workspace").getEl().on("contextmenu",imageContext);rootNode=Ext.getCmp("tree-panel").getRootNode();while(rootNode.childNodes.length>0){rootNode.removeChild(rootNode.item(0))}Ext.getCmp("tree-panel").getRootNode().appendChild(varListing.variables);Ext.getCmp("workspace").plotConfig.dataFile=varListing.dataFile;Ext.getCmp("tree-panel").dataFile=varListing.dataFile;t(Ext.getCmp("workspace").plotConfig);if(Ext.getCmp("fileuploadfield")){filename=Ext.getCmp("fileuploadfield").value;dataType=Ext.getCmp("guessType").value;dataHeader=Ext.getCmp("guessHeader").value?"T":"F";dataSep=Ext.getCmp("guessSep").value=="\t"?"\\t":Ext.getCmp("guessSep").value;dataDec=Ext.getCmp("guessDec").value;if(dataType=="dta"){Q("library(foreign);");var aj='myData <- read.dta("'+filename+'");'}else{if(dataType=="spss"){Q("library(foreign);");var aj='myData <- read.spss("'+filename+'", to.data.frame=T);'}else{if(dataType=="rda"){var aj='myData <- load("'+filename+'");'}else{if(dataType=="xls"){Q("library(gdata);");var aj='myData <- read.xls("'+filename+'", header='+dataHeader+");"}else{var aj="myData <- read."+dataType+'("'+filename+'", header='+dataHeader+', sep="'+dataSep+'", dec="'+dataDec+'");'}}}}Q(aj)}else{Q("# Please download your data manually from google spreadsheets to .csv");Q("myData <- read.csv('myData.csv');")}Ext.getCmp("uploadWindow").close();Ext.getCmp("openDataButton").disable();Ext.getCmp("closeDataButton").enable()}}}},failure:function(ai,aj){ag.hide();Ext.getCmp("importButton").enable();alert("R catched an error: "+aj.result.error)}})}function U(ag){var ak=new Array();for(var aj=0;aj<ag.variableNames.length;aj++){ak[aj]={header:ag.variableNames[aj]}}var ai=new Ext.grid.ColumnModel({columns:ak});var ah=new Ext.data.ArrayStore({fields:ag.variableNames,data:ag.variableData});Ext.getCmp("guessGrid").reconfigure(ah,ai)}function l(aj){var ai=aj;var ah=["%a","%A","%b","%B","%c","%d","%H","%I","%j","%m","%M","%p","%S","%U","%w","%W","%x","%X","%y","%Y"];var ag=["Sat","Saturday","Apr","April","4/17/2010 3:05:45 PM","17","15","03","107","04","05","PM","45","15","6","15","4/17/2010","3:05:45 PM","10","2010"];for(var ak=0;ak<ah.length;ak++){ai=ai.replace(ah[ak],ag[ak])}return(ai)}function D(ag){outputData=[];for(var ah=0;ah<ag.length;ah++){outputData[ah]=[ag[ah],l(ag[ah])]}return outputData}function M(ag){if(ag.target.id=="ggfolder_Numeric"){Ext.MessageBox.show({title:"Convert to numeric",msg:'Are you sure you want to convert variable "'+ag.dropNode.id+'" to Numeric? This will transform all current categories to values 1,2,3,...,etc in alphabetical order.',width:300,buttons:Ext.MessageBox.OKCANCEL,animEl:Ext.getCmp("tree-panel").getEl(),fn:function(aj){if(aj=="ok"){ah(ag.dropNode.id,"Numeric","")}}})}else{if(ag.target.id=="ggfolder_Factor"){Ext.MessageBox.show({title:"Convert to numeric",msg:'Are you sure you want to convert variable "'+ag.dropNode.id+'" to Factor? This will remove any numerical information and create a category for every unique value.',width:300,animEl:Ext.getCmp("tree-panel").getEl(),buttons:Ext.MessageBox.OKCANCEL,fn:function(aj){if(aj=="ok"){ah(ag.dropNode.id,"Factor","")}}})}else{if(ag.target.id=="ggfolder_Date"){if(R){return false}R=new Ext.Window({width:300,height:205,id:"dateWindow",resizable:false,border:false,title:"Convert variable to Date / Time",items:[{height:70,html:"<p>To convert variable <b>"+ag.dropNode.id+'</b> to Date or Time, please choose in which format the date or time is specified in your data. For more information about the conversion codes, visit <a target="_blank" href="http://www.opengroup.org/onlinepubs/009695399/functions/strptime.html">this page</a>.</p>'},{xtype:"form",height:72,autoWidth:true,frame:true,border:false,bodyStyle:"padding: 5px 10px 5px 10px;",labelWidth:100,defaults:{anchor:"100%"},items:[{fieldLabel:"Example Format",triggerAction:"all",id:"exampleDate",xtype:"combo",valueField:"format",displayField:"date",store:{xtype:"arraystore",fields:["format","date"],data:D(["%Y-%m-%d","%Y/%m/%d","%B %d","%d%b%Y","%H:%M:%S","%I:%M:%S %p","Week %W Day %w"])},listeners:{select:function(aj,ak){Ext.getCmp("formatField").setValue(ak.get("format"))}},editable:false,mode:"local",typeAhead:false},{fieldLabel:"Format code",enableKeyEvents:true,xtype:"textfield",id:"formatField",listeners:{keyup:function(an,am){var al=an.getRawValue();var ak=["%a","%A","%b","%B","%c","%d","%H","%I","%j","%m","%M","%p","%S","%U","%w","%W","%x","%X","%y","%Y"];var aj=["Sat","Saturday","Apr","April","4/17/2010 3:05:45 PM","17","15","03","107","04","05","PM","45","15","6","15","4/17/2010","3:05:45 PM","10","2010"];for(var ao=0;ao<ak.length;ao++){al=al.replace(ak[ao],aj[ao])}Ext.getCmp("exampleDate").setValue(al)}}}]}],listeners:{close:function(){R=null}},buttons:[{text:"OK",varName:ag.dropNode.id,handler:function(){ah(this.varName,"Date",Ext.getCmp("formatField").getRawValue())}},{text:"CANCEL",handler:function(){R.close()}}]});R.show(Ext.getCmp("tree-panel").getEl())}}}Ext.getCmp("tree-panel").getNodeById(ag.target.id).expand();function ai(aj,an){theNode=Ext.getCmp("tree-panel").getNodeById(an.inputList.varName).remove(false);newNode={id:theNode.id,text:theNode.text,leaf:true};var am="ggfolder_"+an.inputList.targetType;Ext.getCmp("tree-panel").getNodeById(am).appendChild(newNode);var ak=an.inputList.targetType=="Date"?an.inputList.targetType:an.inputList.targetType.toLowerCase();if(an.inputList.targetType=="Date"){var al="myData$"+an.inputList.varName+" <- as.Date(myData$"+ag.dropNode.id+', format="'+an.inputList.dateFormat+'");'}else{var al="myData$"+an.inputList.varName+" <- as."+ak+"(myData$"+ag.dropNode.id+");"}Q(al);if(R){R.close();R=null}}function ah(al,ak,aj){g("convertVariable",{dataFile:Ext.getCmp("workspace").plotConfig.dataFile,varName:al,targetType:ak,dateFormat:aj},ai,Ext.getCmp("tree-panel").getEl())}return false}function r(){myToken=readCookie("token");if(myToken!=null&&myToken!=""){return myToken}else{var ag=confirm("No valid google session has been found. Do you want to log-in to your Google account now? This will open a new window.");if(ag){theURL="https://www.google.com/accounts/AuthSubRequest?next=http://"+window.location.host+"/R/googleLogin%3Fdomain%3D"+window.location.host+"&scope=https://docs.google.com/feeds/%20http://spreadsheets.google.com/feeds/%20https://docs.googleusercontent.com/&session=1&secure=0";newWin=window.open(theURL);newWin.focus();return false}}}function H(ag){return'<a alt="link to the spreadsheet" target="_blank" href="'+ag+'"> <img src="icons/spreadsheet.gif"></a>'}function J(ag){myToken=r();if(!myToken){return}if(V){return}V=new Ext.Window({width:600,height:400,resizable:false,token:myToken,id:"uploadWindow",title:"Google spreadsheets",frame:true,border:false,layout:"card",activeItem:0,items:[{xtype:"grid",enableHdMenu:false,draggable:false,id:"uploadGrid",enableColumnMove:false,height:337,autoWidth:true,stripeRows:true,columns:[{header:"ResourceId",hidden:true},{header:"name",width:180,sortable:true},{header:"published",sortable:true,width:80},{header:"author",width:100},{header:"email",width:150},{header:"link",renderer:H,width:30}],store:new Ext.data.ArrayStore({fields:[{name:"ResourceId"},{name:"name"},{name:"published"},{name:"author"},{name:"email"},{name:"link"}]}),frame:true}],buttons:[{text:"import",id:"importButton",token:myToken,handler:function(aj){if(!Ext.getCmp("uploadGrid").getSelectionModel().getSelected()){alert("No dataset selected");return}function ai(ak){k(ak.output.dataFile)}thisResource=Ext.getCmp("uploadGrid").getSelectionModel().getSelected().get("ResourceId");thisName=Ext.getCmp("uploadGrid").getSelectionModel().getSelected().get("name");thisToken=this.token;g("importSpreadsheet",{token:myToken,resourceId:thisResource,filename:thisName},ai,Ext.getCmp("uploadWindow").getLayoutTarget())}}],listeners:{beforedestroy:function(){V=null},show:function(){g("listSpreadsheets",{token:myToken},ah,Ext.getCmp("uploadGrid").getEl())}}});V.show(ag);function ah(ai){Ext.getCmp("uploadGrid").getStore().loadData(ai.output.entries)}}var Y=new Ext.tree.TreePanel({border:true,margins:"3 3 0 3",singleExpand:false,enableDD:true,dropConfig:{allowParentInsert:false,appendOnly:true,moveOnly:true,ignoreSelf:true},bodyStyle:"padding: 5px 5px 5px 5px;",id:"tree-panel",region:"center",iconCls:"downArrow",autoScroll:true,animate:true,rootVisible:false,lines:false,useArrows:true,listeners:{nodedragover:function(ag){if(!ag.dropNode.leaf||ag.dropNode.parentNode==ag.target){return false}},beforenodedrop:M},root:new Ext.tree.AsyncTreeNode({id:"root1"})});var E=new Ext.tree.TreeSorter(Y,{});var u={region:"south",border:true,margins:"3 3 3 3",id:"details-panel",height:165,bodyStyle:{background:"#ffffff",padding:"7px"},html:'<div id="generalDetailDiv"> <h1> General options </h1> </div>'};var L={id:"dataPanel",collapsible:true,floatable:false,region:"east",layout:"border",border:true,title:"Data Panel",margins:"5 5 5 5",width:200,listeners:{expand:T,collapse:T},items:[Y,u]};var C={id:"workspace",layout:"fit",region:"center",html:'<div class="start-div"><div style="float:left; margin: 0 0 0 0; padding 0 0 0 0;" ><img src="images/layout-icon.gif" /></div><div style="display: block; margin-left:100px;"> <h2>yeroon.net/ggplot2. Version 0.2.</h2><div><p>How to use:</p><p><b>1. Open a dataset</b>. Make sure every column has a header.</p><p><b>2. Right mouseclick</b> somewhere in this plotarea to open the plot menu.</p> <p><b>3. Map X and Y</b> to a variable and <b>add Geom layers.</b></p><div id="demovideo"><p>Click <a href="http://www.youtube.com/watch?v=pCzQP7kVEOc" target="_blank">Here</a> for a short how-to Demo Video!</p></div></div>',border:true,margins:"5 0 5 0",buttons:[{text:"Draw plot",id:"drawButton",iconCls:"fit",handler:function(){F()}},{text:"Reset",id:"resetbutton",iconCls:"reset",disabled:true,handler:function(){K()}}]};var j=new Ext.grid.GridPanel({id:"layerList",mode:"local",store:new Ext.data.ArrayStore({fields:["id","Geom"],data:[],idIndex:0,refreshData:function(){var ag=this.getRange();this.removeAll();this.add(ag)}}),columns:[new Ext.grid.RowNumberer(),{header:"Geom",width:120,dataIndex:"Geom",sortable:true}],sm:new Ext.grid.RowSelectionModel({singleSelect:true}),viewConfig:{forceFit:true},height:200,border:true,margins:"3 3 0 3",hideHeaders:true,autoScroll:true,listeners:{rowcontextmenu:function(ah,ag,ai){this.getSelectionModel().selectRow(ag);ai.stopEvent();this.getStore().getAt(ag).layerMenu.menu.showAt(ai.getPoint())},contextmenu:function(ah){var ag=ah.getTarget("table");if(!ag){ah.stopEvent();Ext.getCmp("geomMenu").showAt(ah.getPoint())}}},region:"center"});var B={margins:"3 3 3 3",id:"layerDetails",layout:"fit",html:'<div id="detailDiv"> <h1> Layer options </h1> </div>',region:"south",height:165,bodyStyle:{background:"#ffffff",padding:"7px"},border:true};var A={id:"layerPanel",collapsible:true,floatable:false,region:"west",layout:"border",margins:"5 5 5 5",width:200,border:true,title:"Layers Panel",listeners:{expand:function(ag){T(ag);Ext.getCmp("layerList").getStore().refreshData()},collapse:T},items:[j,B]};var I={title:"Syntax",collapsible:true,collapsed:true,titleCollapse:false,floatable:false,header:false,split:true,collapseMode:"mini",layout:{type:"vbox",align:"stretch",pack:"start"},id:"syntaxPanel",region:"south",border:false,items:[{border:false,flex:1,html:Ext.get("historyCmp")},{border:false,height:30,html:Ext.get("syntaxdiv")}],height:120,listeners:{expand:function(ag){N();T(ag)},collapse:T}};function x(ag,ah){if(!ag.checked){Ext.getCmp(ag.panel).expand()}else{Ext.getCmp(ag.panel).collapse()}}function T(ag){Ext.getCmp(ag.id+"CheckBox").setChecked(!ag.collapsed)}function Z(ag,ah){newUrl=ah.get("url");if(V||Ext.getCmp("workspace").plotConfig.dataFile){alert("You cannot switch to a different CPU server in the middle of a session. Please your current dataset and any open windows before switching CPU servers.");return false}c=newUrl}mainMenuBar=new Ext.Toolbar({region:"north",cls:"mainMenuBar",items:["-",{xtype:"button",text:"Open Data",id:"openDataButton",iconCls:"menuOpen",scale:"medium",menu:{items:[{text:"Upload File",iconCls:"icon_csv",handler:function(){a(this.getEl())}},{text:"Google Spreadsheet",iconCls:"icon_spreadsheet",disabled:false,handler:function(){J(this.getEl())}},{text:"Database",iconCls:"icon_database",disabled:true}]}},{text:"Close Data",iconCls:"menuClose",id:"closeDataButton",disabled:true,scale:"medium",handler:function(){var ag=confirm("Are you sure you want to close this dataset?");if(ag){window.location.reload()}}},"-",{text:"Export PDF",id:"pdfbutton",disabled:true,iconCls:"menuPDF",scale:"medium",handler:function(){ad()}},{text:"Export SVG",id:"svgbutton",disabled:true,iconCls:"menuSVG",scale:"medium",handler:function(){S()}},"-",{xtype:"button",text:"View",iconCls:"menuView",scale:"medium",menu:{defaults:{checked:true,align:"left",handler:x},items:[{text:"layer panel",panel:"layerPanel",id:"layerPanelCheckBox"},{text:"data panel",panel:"dataPanel",id:"dataPanelCheckBox"},{text:"code panel",panel:"syntaxPanel",id:"syntaxPanelCheckBox",checked:false}]}},"->",{xtype:"tbspacer",width:40},"-",{text:"Cite",iconCls:"menuCite",scale:"medium",handler:function(){X()}},"-",{text:"Help / About",iconCls:"menuHelp",scale:"medium",handler:function(){window.open("http://www.jeroenooms.com/ggplot2.html")}},"-"]});new Ext.Viewport({id:"viewport",bodyStyle:"background: none",layout:"border",cls:"viewport",title:"Ext Layout Browser",items:[{id:"menuBarPanel",region:"north",height:0,tbar:mainMenuBar,border:false},L,C,A,I],renderTo:Ext.getBody()});p();Ext.getCmp("workspace").plotConfig=new W();var ab;function X(){if(!ab){ab=new Ext.Window({closeAction:"hide",iconCls:"bib",title:"Citing lme4",closable:true,layout:"fit",height:400,width:700,autoScroll:false,items:{border:false,applyTo:"citeDiv"}})}ab.show()}Q("# Welcome to yeroon.net/ggplot version 0.2!");Q("# To install ggplot2, do: install.packages('ggplot2')");Q("library(ggplot2);");b("ggplot()")});