<?xml version="1.0" encoding="UTF-8"?>
<Module>
<ModulePrefs title="Plot">
  <!-- // not sure what this is  <Require feature="idi" /> -->
    <Require feature="locked-domain" />  
    <Require feature="dynamic-height"/>
    <Require feature="opensocial-0.8"/> 
    <Require feature="minimessage"/>

</ModulePrefs>
<Content type="html"><![CDATA[

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="http://sky.astro.washington.edu/gadgets/js/gDataInterface.js" type="text/javascript"></script>
<script src="http://sky.astro.washington.edu/gadgets/js/astroObjectLib.js" type="text/javascript"></script>

<script type="text/javascript">
    

// Plot (pl) object is global
var pl = null,
    debug = true;

// Writes to the console if debug (global) is true  
function debugLog(msg){
    if ((debug === true) && (window.console && console.log)) { 
         console.log(GADGET_NAME + ": " + msg);
    }
    return;
}



// GLOBAL CONSTANTS
var GADGET_NAME = "Plot_Scatter" + "_" + Math.floor(Math.random()*100000+1).toString();

// Writes to the console if debug (global) is true  
function debugLog(msg){
    if ((debug === true) && (window.console && console.log)) {
        console.log(GADGET_NAME + ": " + msg);
    }
    return;
}


// create InputCoords object
function init(){
    pl = new Plotter();
    google.load('visualization', '1', {packages: ['ScatterChart']});
    google.setOnLoadCallback(pl.testPlot);
}


function Plotter(){
    var my = new Object();
    // CONSTANTS
    var DEFAULT_NAMESPACE = "NS1",
        MM_TIMER_DURATION = 4;
    // PRIVATE
    var _namespaceList = [ DEFAULT_NAMESPACE ];      // list of our current Namespaces. Just init with the default
    
    // Private Helper Variables
    var di = new gDataInterface(GADGET_NAME, DEFAULT_NAMESPACE); // make dataInterface object, init with default
    var miniMsg = new gadgets.MiniMessage();// make MiniMessage object

    // INIT

    var msg = miniMsg.createStaticMessage("Attempting to register gadget...");
    gadgets.window.adjustHeight();
    doRegistration(_namespaceList);
    
    
    // REGISTRATION stuff
    // do complete registration for all namespaces in the array
    function doRegistration(namespaceArray){
        // TODO: check that namespaceArray is actually an array
        for (var i=0, len=namespaceArray.length; i<len; i++){
            registerMe(namespaceArray[i]);
        }
    }
    // register this gadget in a particular namespace
    function registerMe(namespaceName){
        // First, Register the gadget with success and failure callbacks
        di.registerGadget(namespaceName, function(){continueRegistration(namespaceName);}, 
                                                function(){registrationFailure(namespaceName);});
    }    
    
    // Callback after a successful registration of this gadget in a namespace
    // Displays messages and registers variables
    function continueRegistration(namespaceName){
        debugLog('Registration Successful!');
        if (msg) {
            miniMsg.dismissMessage(msg);
            // free up msg
            msg = null;
            miniMsg.createTimerMessage("Registration Succesful.", MM_TIMER_DURATION);
        }
        registerVariables(namespaceName);
        // di.registerVariable();
        // di.addTrigger();
    }
    
    // Callback after a failure of registration
    // displays message showing failure
    function registrationFailure(namespaceName){
        debugLog('Registration was total failure!');
        miniMsg.dismissMessage(msg);
        miniMsg.createDismissibleMessage("Unable to register gadget.\nWe cannot communicate with other gadgets.");
    }
    
    // Registers variables, and if successful, calls registerTriggers
    function registerVariables(namespaceName){
        debugLog('Attempting to register variables...');
        var varList = [ "VP_Coord", "Active_Point_List", "VP_Point_List" ] // list of variables to register

        for (var i=0, len=varList.length; i<len; i++) {
            // TODO: should we do this for every namespace?
            if (di.registerVariable(namespaceName, varList[i], null)) {
                debugLog('Successfully registered variable "' + varList[i] + '"');
                registerTriggers(namespaceName);
            }
            else {
                debugLog('FAILED to register variable "' + varList[i] + '"');
            }
        }
    }
    
    // registers Triggers
    function registerTriggers(namespaceName){
        // none to register
    }
 

    my.testPlot = function() {
        // create datatable
        var dt = new google.visualization.DataTable();

        // make some random junky data points
        // in this case they are ra's and dec's
        // we will also add them to the VP_Point_List so they show up as placemarks
        var pList = di.readVariable(DEFAULT_NAMESPACE, "VP_Point_List"); // grab the current (plotted) points list
        if (pList === null){
            pList = new UW.astro.UniqIdList();
        }
        dt.addColumn('number', 'ra');
        dt.addColumn('number', 'dec');
        numRows = 20;
        dt.addRows(numRows);
        for (var i=0; i<numRows-1; i++){
            ra = Math.floor(Math.random() * 24);
            dec = Math.floor(Math.random() * 180 - 90);
            dt.setValue(i,0,ra);    // set random ra
            dt.setValue(i,1,dec); // set random dec
            cc = new UW.astro.CelestialCoordinate(ra, dec);
            pList.append(cc);

        }
        // plot all the points on the scatter plot
        var splot = new google.visualization.ScatterChart(document.getElementById('visualization'));
        splot.draw(dt,{titleX: 'RA', titleY: 'dec', legend: 'none'});
        
        // add points to VP as placemarks
        di.writeVariable(DEFAULT_NAMESPACE, "VP_Point_List", pList);

        // add to the 'click' event on the scatter plot
        // we will make the VP zoom to that point
        google.visualization.events.addListener(splot, 'select', 
                        function(){
                            var sel_row = splot.getSelection()[0].row;
                            var sel_ra = dt.getValue(sel_row, 0);
                            var sel_dec = dt.getValue(sel_row, 1);
                            cc = new UW.astro.CelestialCoordinate(sel_ra, sel_dec);
                            di.writeVariable(DEFAULT_NAMESPACE, "VP_Coord", cc);    // make the viewport zoom to this point
                            
                            });

    }

    return my;
}


    gadgets.util.registerOnLoadHandler(init); 


</script>
<div id="divSelections" style="width: 100%;">
    <table> 
    <TBODY>
        <TR>
            <td>
 <!--               <input id="btGetObjectsInVP" onclick="pl.GetObjectsInVP();" type="button" value="Get Objects in Viewport"/>  -->
            </td> 
        </TR> 
    </TBODY>
    </table>

</div>
<div id="visualization" style="width: 100%; height: 100%;">
  <img src="images/spinnerGrey.gif" />
</div>
  
  ]]>
 </Content>
</Module>
