/**
 *  DOWNLOAD Tools EXT Functions -- window vars / forms
 */

var form1 = new Ext.form.FormPanel({
    width:250,
    height:75,
    hideLabels:true,
    items:[{
        xtype:"multiselect",
        name:"multiselect",
        fieldLabel:"",
        delimiter:',',
        dataFields:["code", "desc"],
        data:[["tm2", "TMY Format"], ["csv", "CSV Format"]],
        valueField:"code",
        displayField:"desc",
        width:250,
        height:100,
        allowBlank:false
    }]
});

var form2 = new Ext.form.FormPanel({
    width:250,
    hideLabels:true,
    autoScroll:true,
    items:[{
         xtype:"itemselector",
         name:"itemselector",
         fieldLabel:"",
         drawUpIcon:false,
         drawDownIcon:false,
         drawLeftIcon:true,
         drawRightIcon:true,
         drawTopIcon:false,
         drawBotIcon:false,
         dataFields:["code", "desc"],
         fromData:[["1998", "1998"], ["1999", "1999"], ["2000", "2000"], ["2001", "2001"], ["2002", "2002"],
                   ["2003", "2003"], ["2004", "2004"], ["2005", "2005"],["TDY","TDY"]],
         toData:[],
         msWidth:85,
         msHeight:195,
         valueField:"code",
         displayField:"desc",
         imagePath:"assets/images/",
         toLegend:"Selected",
         fromLegend:"Available",
         autoScroll:true
    }]
});


var download_border = new Ext.Panel({
     layout:'border',
     items: [{
         region: 'north',
         hieght:5
     },{
         title: '2. Select Years',
         region: 'south',
         autoHeight:true,
         minSize: 75,
         maxSize: 250,
         //autoScroll:true,
         items:form2
     },{
         title: '1. Select Formats:',
         region:'center',
         width: 250,
         height:50,
         minSize: 100,
         maxSize: 300,
         items:form1
     }]
});


function openDload(feature) {
    var lat = feature.y;
    var lon = feature.x;
    var latlon = new OpenLayers.LonLat(lon,lat);
    latlon.transform( map.getProjectionObject(), map.displayProjection);
    
    dWin = new Ext.Window({
        title: 'Download Window',
        closable:false,
        width:215,
        height:400,
        resizable:true,
        modal:true,
        shadow:true,
        shadowOffset:10,
        //border:false,
        plain:true,
        layout: 'fit',
        items: download_border,
        buttons: [{
            text:'Submit',
            disabled:false,
            // send a request containing download years
            handler: function(){
                doDownload(latlon.lat,latlon.lon);
            }
          },{
            text: 'Close',
            handler: function(){
            dWin.hide();
         }
      }]
    
   });
   dWin.show();
 
}


function doDownload(lat,lon){
    var formats = form1.getForm().getValues(true);
    if(formats == null) {formats = 'csv';}
    var years   = form2.getForm().getValues(true);

    var short_lat = parseInt( Math.abs(lat) );
    if( (short_lat % 2) > 0 ) --short_lat;

    var short_lon= parseInt( Math.abs(lon) );
    if( (short_lon % 2) > 0 ) --short_lon;
    short_lon += 2;

    var dir = short_lon +''+ short_lat;

    var glat = new Number ( parseInt( ( Math.abs(lat) * 10 ) ) );
        glat = glat.toString().concat( 5 );

    var glon = new Number ( parseInt( ( Math.abs(lon) * 10 ) ) );
        glon = glon.toString().concat( 5 );
        if (glon.length < 5) glon = '0' + glon;

    var grdcode = glon + glat;
    var pStr = "lat=" +lat+ "&lon=" +lon+ "&dir=" +dir+ "&gridcode=" +grdcode+ "&"+formats+"&"+years;
    
    new OpenLayers.Ajax.Request("assets/php/getDownloads.php?" + pStr,
         {  
             onComplete: sendDownload,
             requestHeaders: ['Content-type', 'application/text']
         }
    );
    return false;
}


function sendDownload(request){
    dWin.hide();
    var re      = new RegExp(/C[a-z]+/); // matches the word 'Cannot' to indicate an error
    var repText = request.responseText;
    var m       = re.exec(repText);
    var link    = "tmp/" + repText;
    if (m == null) {
         var win = new Ext.Window({
            title:'Click on the link to download your data',
            width:275,
            height:50,
            html:'<center><a href="'+link+'">Download Data</a><center>'
         });
         win.show();
         //window.open("tmp/"+repText);
    } else {
         alert("Request Failed: "+request.responseText);
    }
}

