<?xml version="1.0" encoding="UTF-8" ?>
<!-- flickrAstrometry.xml -->
<!-- Author: Conor Sayres (csayres@uw.edu) -->
<Module>
<ModulePrefs title="Flickr Astrometry" 
    height="500"
    scrolling="true">
     <Require feature="dynamic-height"/>
     <Require feature="opensocial-0.9"/> 
     <Require feature="minimessage"/>
     <Require feature="settitle"/>
</ModulePrefs> 

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


<!--
  jQuery library
-->
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<!--
  jCarousel library
-->
<script type="text/javascript" src="text/javascript" src="js/jquery.jcarousel.min.js"></script>

<!--
  jCarousel skin stylesheet
-->
<link rel="stylesheet" type="text/css" href="css/skins/ie7/skin.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/dragdrop/dragdrop-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.8.1/build/slider/slider-min.js"></script>

<style type="text/css">

#mycarousel .jcarousel-item-placeholder {
    background: transparent url(images/loading-small.gif) 50% 50% no-repeat;
}
#slider-bg {

    background:url(js/yui/build/slider/assets/bg-fader.gif) 5px 0 no-repeat;
}

#info{
position:absolute;
top: 10px;
left: 300px;
border-width:2px;
}



</style>

<script src="js/DataInterface.js" type="text/javascript"></script>
<script src="js/widgetlib1.js" type="text/javascript"></script>
<script src="js/astroObjectLib.js" type="text/javascript"></script>

<link href="css/style.css" rel="stylesheet" type="text/css" />



<script type="text/javascript">

var tq = null,
    DEBUG = false;

var GADGET_NAME = "FlickrAstrometry" + "_" + Math.floor(Math.random()*100000).toString();


function debugLog(msg){ if(DEBUG){UW.astro.debugLog(GADGET_NAME + ": " + msg);}}

// create gadget object
function init(){
    gadgets.window.setTitle("Flickr Astrometry");
    tq = new NameResolve();
    gadgets.window.adjustHeight();
}

function NameResolve(){
    var my = new Object();
    var opac = 'ff';
    // CONSTANTS
    

    // PRIVATE
    var _namespaceList = [ UW.astro.DEFAULT_NAMESPACE ];      // list of our current Namespaces. Just init with the default
    
    // Private Helper Variables
    var di = new UW.astro.DataInterface(GADGET_NAME); // make dataInterface object, init with default

    // INIT
    di.registerMe( { namespaceList : _namespaceList,
                    variableList : [ "Viewport_Center_Coordinate","img_ovly","kml_opac" ],
                    triggerList : [],
                } );
    
    
    function mycarousel_itemLoadCallback(carousel, state)
    {
        if (carousel.prevFirst != null) {
            // Remove the last visible items to keep the list small
            for (var i = carousel.prevFirst; i <= carousel.prevLast; i++) {
                // jCarousel takes care not to remove visible items
                carousel.remove(i);
            }
        }
    
        var per_page = carousel.last - carousel.first + 1;
        var currPage = 0;
        var f,l;
        var cr = carousel;
    
        for (var i = carousel.first; i <= carousel.last; i++) {
            var page = Math.ceil(i / per_page);
    
            if (currPage != page) {
                currPage = page;
    
                f = ((page - 1) * per_page) + 1;
                l = f + per_page - 1;
    
                f = f < carousel.first ? carousel.first : f;
                l = l > carousel.last ? carousel.last : l;
    
                if (carousel.has(f, l)) {
                    continue;
                }
    
                mycarousel_makeRequest(carousel, f, l, per_page, page);

            }
        }
    };


    function mycarousel_makeRequest(carousel, first, last, per_page, page)
    {
        // Lock carousel until request has been made
        carousel.lock();
        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&group_id=387956@N23&extras=url_m,machine_tags&tags=Astrometrydotnet:status=solved&api_key=4ca112a2ac8348fc0c3f85e3ecb6a2e9&page=" + page + "&per_page=" + per_page + "&format=json&jsoncallback=?", function(data) {
               
                mycarousel_itemAddCallback(carousel, first, last, data, page);
            }); 

    }
    
 
    function mycarousel_itemAddCallback(carousel, first, last, data, page)
    {
        carousel.unlock();
        // Set size
      // change this to work!!!!!!!!!  carousel.size($('photos', data).attr('total'));
        
        var per_page = carousel.last - carousel.first + 1;
    
        for (var i = first; i <= last; i++) {
            var pos = i - 1;
            var idx = Math.round(((pos / per_page) - Math.floor(pos / per_page)) * per_page);
 
            carousel.add(i, mycarousel_getItemHTML(data.photos.photo[idx].url_m,data.photos.photo[idx].id));
        }
    };
    
    /**
     * Global item html creation helper.
     */
     


    function mycarousel_getItemHTML(photo,id)
    {
 
         var url = photo;
         var id  = id;

         return '<a onmouseover="tq.roll(' + id.toString() + ',\'' + url + '\')" onClick="tq.sendIMG(' + id.toString() + ',\'' + url + '\')"> <img src="' + url + '" border="0" width="75" height="75" /></a>';
    };
    (function() {
    var Event = YAHOO.util.Event,
        Dom   = YAHOO.util.Dom,
        lang  = YAHOO.lang,
        slider, 
        bg="slider-bg", thumb="slider-thumb", 
        valuearea="slider-value", textfield="slider-converted-value"

    // The slider can move 0 pixels up
    var topConstraint = 0;

    // The slider can move 200 pixels down
    var bottomConstraint = 200;

    // Custom scale factor for converting the pixel offset into a real value
    var scaleFactor = 1.5;

    // The amount the slider moves when the value is changed with the arrow
    // keys
    var keyIncrement = 20;

    var tickSize = 20;

    Event.onDOMReady(function() {

        slider = YAHOO.widget.Slider.getHorizSlider(bg, 
                         thumb, topConstraint, bottomConstraint, 20);

        // Sliders with ticks can be animated without YAHOO.util.Anim
        slider.animate = true;

        slider.getRealValue = function() {
            return Math.round(this.getValue() * scaleFactor);
        }

        slider.subscribe("change", function(offsetFromStart) {

            var valnode = Dom.get(valuearea);
            var fld = Dom.get(textfield);
            var num=slider.getRealValue()/30.0; //from offsetFromStart
            //alert(num)
            if (num==0){
            opac='fe';
            }
            if (num==1){
            opac='e6';
            }
            if (num==2){
            opac='cd';
            }
            if (num==3){
            opac='b3';
            }
            if (num==4){
            opac='9b';
            }
            if (num==5){
            opac='82';
            }
            if (num==6){
            opac='68';
            }
            if (num==7){
            opac='50';
            }
            if (num==8){
            opac='37';
            }
            if (num==9){
            opac='1d';
            }
            if (num==10){
            opac='00';
            }
            //alert('moved')
            di.writeVariable(UW.astro.DEFAULT_NAMESPACE,"kml_opac",opac);
            if (di.writeVariable(UW.astro.DEFAULT_NAMESPACE, "kml_opac", opac)){
                  debugLog('Wrote variable "kml_opac"');
            };
            // Display the pixel value of the control
            //alert(offsetFromStart);
            valnode.innerHTML = offsetFromStart;
            //alert('stop');
            // use the scale factor to convert the pixel offset into a real
            // value
            var actualValue = slider.getRealValue();

            // update the text box with the actual value
            fld.value = actualValue;

            // Update the title attribute on the background.  This helps assistive
            // technology to communicate the state change
            Dom.get(bg).title = "slider value = " + actualValue;
             

        });
        slider.subscribe("slideStart", function() {
                YAHOO.log("slideStart fired", "warn");
            });

        slider.subscribe("slideEnd", function() {
                YAHOO.log("slideEnd fired", "warn");

               // alert(slider.getRealValue());
            });

        // Listen for keystrokes on the form field that displays the
        // control's value.  While not provided by default, having a
        // form field with the slider is a good way to help keep your
        // application accessible.
        Event.on(textfield, "keydown", function(e) {

            // set the value when the 'return' key is detected
            if (Event.getCharCode(e) === 13) {
                var v = parseFloat(this.value, 10);
                v = (lang.isNumber(v)) ? v : 0;

                // convert the real value into a pixel offset
                slider.setValue(Math.round(v/scaleFactor));
            }
        });
        
        // Use setValue to reset the value to white:
        Event.on("putval", "click", function(e) {
            slider.setValue(100, false); //false here means to animate if possible
        });
        
        // Use the "get" method to get the current offset from the slider's start
        // position in pixels.  By applying the scale factor, we can translate this
        // into a "real value
        Event.on("getval", "click", function(e) {
            YAHOO.log("Current value: "   + slider.getValue() + "\n" + 
                      "Converted value: " + slider.getRealValue(), "info", "example"); 
        });
    });
})();

    jQuery(document).ready(function() {
        jQuery('#mycarousel').jcarousel({
            itemLoadCallback: mycarousel_itemLoadCallback
        });
    });



    //METHODS
    my.roll=function(id,url){
    //alert('went')
    // $('#test').fadeIn('slow', function() {
    document["big_img"].src=url;      
  // Animation complete
  //    })
    //document["big_img"].src=url;
    //document["big_img"].id=id;
 

    }
    my.sendCoord=function(id){
         $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&photo_id=" + id +"&api_key=4ca112a2ac8348fc0c3f85e3ecb6a2e9&format=json&jsoncallback=?", function(data2) {
         list=data2.comments.comment;
         for (i in list){
            name=list[i].authorname           
            if ((name.toString()).search("astrometry.net")!=-1){
              //alert(list[i]._content)
              var dataLine = list[i]._content.split(/\n/)[1].split(/,/);
              ra=dataLine[1].match(/[-\d\.]+/)
              dec=dataLine[2].match(/[-\d\.]+/)
              debugLog("Writing Coods...");
              ra = (ra/15).toString();  //decimal hours
              dec = dec.toString();  //decimal degrees
              var coord = new UW.astro.CelestialCoordinate(ra, dec);
              if (di.writeVariable(UW.astro.DEFAULT_NAMESPACE, "Viewport_Center_Coordinate", coord)){
                debugLog('Wrote variable "Viewport_Center_Coordinate"');
              
              }
            }
         } 

         })        
    }
    my.sendIMG=function(id,url){
         var img_ovly=new Array();
         $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&photo_id=" + id +"&api_key=4ca112a2ac8348fc0c3f85e3ecb6a2e9&format=json&jsoncallback=?", function(data2) {
           //owner=data2.photo.ownername;
           //alert(data2.toSource())
           list=data2.comments.comment;
           for (i in list){
              name=list[i].authorname
              if ((name.toString()).search("astrometry.net")!=-1){
                //alert(list[i]._content)

//parse below and make new------------------------------------

                var dataLine = list[i]._content.split(/\n/);
               // alert(dataLine[2].toSource());
                var ra=dataLine[2].split(/,/)[2].split("(")[1];
                var dec=dataLine[2].split(/,/)[3].split(/\)/)[0];
               // alert('ra:'+ra+'   '+'dec:'+dec)
                var lng=dataLine[1].split(/,/)[1].match(/[-\d\.]+/);
                var lat=dataLine[1].split(/,/)[2].match(/[-\d\.]+/);
                //alert(lat)
                //alert(lng)
                //alert(dataLine[7].toSource());
                var rotation = Number(dataLine[3].match(/[-\d\.]+/))*(-1.0)+180.0; 
                img_ovly[11]=rotation;                          
                if(rotation>180.0){
                   rotation=rotation-360.0;
                }

                //alert(rotation)
                var owner=null;
                var fov = new Array();
                var field = dataLine[8].toString().split(":")[1];
                fov[0] = dataLine[8].split(/x/)[0].match(/[\d\.]+/); 
                fov[1] = dataLine[8].split(/x/)[1].match(/[\d\.]+/);
                if(dataLine[8].match('arcminutes')){
                fov[0]=fov[0]/60.0;
                fov[1]=fov[1]/60.0;
                }
                if (fov[0]<=fov[1]){
                img_ovly[10]=fov[1];
                }
                else{
                img_ovly[10]=fov[0];
                }
                var north=Number(lat)+0.5*fov[1];
                var south=Number(lat)-0.5*fov[1];  //arcmin to deg
                var east=Number(lng)+0.5*fov[0]-180.0;
                var west=Number(lng)-0.5*fov[0]-180.0; 
                //alert(north)
                //alert(south)
                //alert(east)
                //alert(west)
                //alert(rotation)
                debugLog("Writing Image Data...");
                //var transp=prompt("Enter Opacity (00-ff):")
                //var img_ovly = new Array();
                //img_ovly[0]=url
                //alert(img_ovly[0])
                img_ovly[1]=north
                img_ovly[2]=south
                if(dataLine[7].match('Normal')){  //if parity is wrong switch east with west
                img_ovly[4]=east
                img_ovly[3]=west
                }
                else{
                img_ovly[3]=east
                img_ovly[4]=west
                }
                img_ovly[5]=rotation
                img_ovly[6]=opac;
                img_ovly[7]=lat;
                img_ovly[8]=lng;
         
                $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=" + id +"&api_key=4ca112a2ac8348fc0c3f85e3ecb6a2e9&format=json&jsoncallback=?", function(data3) {
                owner=data3.photo.owner.username;
                img_ovly[9]=owner;
                //alert(img_ovly[9]);
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&photo_id=" + id +"&api_key=4ca112a2ac8348fc0c3f85e3ecb6a2e9&format=json&jsoncallback=?", function(data4) {
                list2=data4.sizes.size;
                //alert(list2.toSource())
                  for (i in list2){
                  var size=list2[i].label;
                  //alert(size.toString());
                  if (size.toString()=='Medium'){
                  //alert(list2[i].source);
                  var url=list2[i].source;
                  img_ovly[0]=url;
                  }
                  if (size.toString()=='Large'){
                  //alert(list2[i].source);
                  var url=list2[i].source;
                  img_ovly[0]=url;
                  }
                  if (size.toString()=='Original'){
                  //alert(list2[i].source);
                  var url=list2[i].source;
                  img_ovly[0]=url;
                  }
                }
                document.getElementById('author').innerHTML=' '+img_ovly[9];
                document.getElementById('ra').innerHTML=' '+ra;
                document.getElementById('dec').innerHTML=' '+dec;
                document.getElementById('field').innerHTML=' '+field;
                di.writeVariable(UW.astro.DEFAULT_NAMESPACE,"img_ovly",img_ovly)
                if (di.writeVariable(UW.astro.DEFAULT_NAMESPACE, "img_ovly", img_ovly)){
                  debugLog('Wrote variable "img_ovly"');
                }
                });
                });


              
              
            
         } 

         }

     });
     }         
    return my;
}

gadgets.util.registerOnLoadHandler(init); 


</script>


<!--

<p>Pixel value: <span id="slider-value">0</span></p>

<p>Converted value:
<input autocomplete="off" id="slider-converted-value" type="text" value="0" size="4" maxlength="4" />
</p>


<button id="putval">Change slider value to 100 (converted value 150)</button>

<button id="getval">Write current value to the Logger</button> 
-->


<div id="wrap" style="height:375px;width:100%">
    <div id="disp" class="disp">
    <a><img src="images/mousover.jpg" id="test" name="big_img" height="245px" width="245px"/></a>
 </div>
<div id="slider-bg" class="yui-h-slider" tabindex="-1" title="Slider">
    <div id="slider-thumb" class="yui-slider-thumb"><img src="js/yui/build/slider/assets/thumb-n.gif"></div>
</div>
<div id="info" height="50px">
<p><u>Photo Info</u><p>
<p>Author:<b id="author"></b></p>
<p>RA:    <b id="ra"></b></p>
<p>DEC:   <b id="dec"></b></p>
<p>Field: <b id="field"></b></p> 

</div>
  <div id="mycarousel" class="jcarousel-skin-ie7">

    <ul>
      <!-- The content will be dynamically loaded in here -->
    </ul>

  </div>


]]></Content>
</Module>
