
Ext.BLANK_IMAGE_URL = './ext-2.1/resources/images/default/s.gif';

Ext.namespace('recipeBook20');

recipeBook20.recipes = function() {

  var deliciousStore;
  var recipesGrid;

  function renderLink(value, p, record) {
      return String.format('<a href="{1}"><img src="{0}"/></a>',
                value.split('/').splice(0,3).join('/')+'/favicon.ico',
                value);
  };
  
  function renderName(value, p, record) {
    return String.format('<b><a href="{0}">{1}</a></b>',
              record.get('url'),
              value);
  }

  return {
    loadPage : function(selectedIngredients) {
      var params = "";
      for(var i=0; i<selectedIngredients.length; i++) {
        params += "+ingredient."+selectedIngredients[i];
      }
      deliciousStore.proxy.url = 'http://feeds.delicious.com/v2/json/pbackx/recipes'+params;
      deliciousStore.load();
    },
    
    init : function() {
      deliciousStore = new Ext.data.Store({
        proxy: new Ext.data.ScriptTagProxy({
          url : 'http://feeds.delicious.com/v2/json/pbackx/recipes'
        }),
        reader: new Ext.data.JsonReader({
          }, Ext.data.Record.create([
              { name : 'url',   mapping : 'u' },
              { name : 'title', mapping : 'd' },
              { name : 'description', mapping : 'n'}
          ])
        )
      });
  
      recipeBook20.recipes.loadPage([]);
  
      recipesGrid = new Ext.grid.GridPanel({
        height:500,
        width:600,
        title:'recipes',
        store: deliciousStore,
        cm: new Ext.grid.ColumnModel([{
          id: 'url',
          header: 'Link',
          dataIndex: 'url',
          renderer: renderLink,
          sortable: false,
          width: 5
        },{
          id: 'title',
          header: 'Recipe name',
          dataIndex: 'title',
          renderer: renderName,
          sortable: true
        }]),
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        viewConfig: {
          forceFit:true,
          enableRowBody:true,
          getRowClass : function(record, rowIndex, p, store){
            p.body = '<p>'+record.data.description+'</p>';
            return 'x-grid3-row-expanded';
          }
        },
        bbar: [{
          text: 'add recipe',
          handler: function(btn) {
            window.open("mailto:peter.backx@gmail.com");
          }
        }]
      });

      recipesGrid.render('recipeContent');
    } // end of init
  }
}(); // end of recipes

recipeBook20.ingredients = function() {
  var ingredientStore;
  var ingredientWindow;
  var ingredientForm;
  var selectedIngredients = new Array();
  var userName = "pbackx";

  function getIngredientForm(records) {
    var ingredientItems = [];

    for(var i=0; i<records.length; i++) {
      ingredientItems[ingredientItems.length] = new Ext.form.Checkbox ({
        fieldLabel: records[i].get('title'),
        name: records[i].get('title'),
        listeners: {
          'check' : changeIngredientSelection
        }
      });
    }

    ingredientForm = new Ext.FormPanel({
        labelWidth: 100, // label settings here cascade unless overridden
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        width: 120,
        defaults: {width: 20},
        defaultType: 'checkbox',
        autoScroll: true,
        items: ingredientItems
    });
  
    return ingredientForm;
  }

  function changeIngredientSelection(checkbox, checked) { 
    if(checked) {
      selectedIngredients.push(checkbox.getName());
    } else {
      selectedIngredients.remove(checkbox.getName());  
    }
    recipeBook20.recipes.loadPage(selectedIngredients); // probably better to have an event listener in app do this
  }

  return {
    init: function() {
      ingredientStore = new Ext.data.Store({
        proxy: new Ext.data.ScriptTagProxy({
              url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=7Lxs970t3RGOzUHQy6ky6g&_render=json&username='+userName,
              callbackParam: '_callback'
        }),
        reader: new Ext.data.JsonReader({
              totalProperty : 'count',
              root : 'value.items'
          }, Ext.data.Record.create([ {name : 'title' } ])
        )
      });
  
      ingredientStore.load({
        callback: function(records, options, success) {
          if(success) {
            ingredientWindow.remove(ingredientWindow.items.items[0].id);
            ingredientWindow.add(getIngredientForm(records));
            ingredientWindow.doLayout();
          } else {
            alert("Failed to connect to Yahoo! Pipes");
          }
        }
      });

      ingredientWindow = new Ext.Window({
        layout: 'fit',
        title: 'Select ingredient(s)',
        closable: false,
        resizable: true,
        x: 700,
        y: 20,
        width:200,
        height:400
      });
      ingredientWindow.add(new Ext.form.Label({
        text : 'loading'
      }));

      ingredientWindow.show(document.body);
    } // end of init
  }
}(); // end of ingredients

recipeBook20.app = function() {
//var addWindow;
//function addRecipe() {
//  if(!addWindow) {
//    addWindow = new Ext.Window({
//      closeAction:'hide',
//      layout: 'fit',
//      title: 'Enter the URL of the recipe you want to add',
//      width:500,
//      height:100,
//      items: new Ext.FormPanel({
//        id: 'addRecipeForm',
//        labelWidth: 75,
//        width: 410,
//        frame:true,
//        defaults: {width: 330},
//        defaultType: 'textfield',
//        items: [{
//          fieldLabel: 'URL',
//          allowBlank: false
//        }],
//        buttons: [{
//                    text:'Submit',
//                    handler: function() {
//                      alert("submit");
//                    }
//                },{
//                    text: 'Close',
//                    handler: function(){
//                        addWindow.hide();
//                    }
//        }]
//      })
//    });
//  }
//  addWindow.show(document.body);
//}

  // public space
  return {
    // public properties, e.g. strings to translate
 
    // public methods
    init: function() {
      recipeBook20.ingredients.init();
      recipeBook20.recipes.init();
    }

  };

}(); //enf of app

Ext.onReady(recipeBook20.app.init, recipeBook20.app);
