dojo.require("dojo.data.ItemFileWriteStore");
dojo.addOnLoad(setup_create_list);

var CreateList;

function setup_create_list() {
  dojo.byId("errors").innerHTML = "";
  CreateList = {
    store: new dojo.data.ItemFileWriteStore({data: {
      identifier: "name",
      label: "name",
      items: [] }
      }),

      makeTable: function(items, request) {
        var h = '<table cellspacing="0" cellpadding="0" class="itemsTable">';
        h += '<thead><tr><th class="nameCol">' + gettext('Name') + '</th><th>' + gettext('Qtty') + '</th></tr></thead>';
        for (var i = 0; i < items.length; i++) {
          var item = items[i];
          var itemName = CreateList.store.getLabel(item);
          var itemNote = CreateList.store.getValue(item, "note", "");
          rowClass = i%2 ? "evenRow" : "oddRow";
          h += '<tr><td class="nameCol ' + rowClass + '"><a href="javascript:void(0)" onclick="CreateList.loadItem(\'' + itemName + '\')">' + itemName + '</a>';
          if (itemNote.length > 0) {
            h+='<br><div class="itemNote">' + itemNote + '</div>';
          }
          h += '</td><td class="' + rowClass + '">' + CreateList.store.getValue(item, "qtty", "") + '</td></tr>';
        }
        h += '</table>';
        //  console.log(h);
        dojo.byId("tableDiv").innerHTML = h;
      },

      saveDone: function() {
        CreateList.store.fetch({sort: [{attribute: "name"}]  , onComplete: CreateList.makeTable});
        dojo.byId("nameField").focus();
      },

      checkItem: function(items, request) {
        var itemForm = dijit.byId("itemForm");
        if (items.length == 0) {
          // Add new item
          dijit.byId("nameField").attr('value', CreateList.toTitleCase(itemForm.attr('value').name));
          CreateList.store.newItem(itemForm.attr('value'));
        } else {
          // Change the qtty on the existing item
          CreateList.store.setValue(items[0], "qtty", itemForm.attr('value').qtty);
          CreateList.store.setValue(items[0], "note", itemForm.attr('value').note);
        }
        CreateList.store.save({onComplete: CreateList.saveDone});
        itemForm.reset();
        dijit.byId("addButton").attr('disabled', false);
      },

      addItem: function(evt) {
        // Remove error message
        dojo.byId("errors").innerHTML = '';
        var itemForm = dijit.byId("itemForm");
        // Check for existing item
        if (itemForm.attr('value').name.length > 0 && dijit.byId("qttyField").isValid()) {
          dijit.byId("addButton").attr('disabled', true);
          CreateList.store.fetch({query:{name:itemForm.attr('value').name}, queryOptions:{ignoreCase: true}, onComplete:CreateList.checkItem, onError:function(errorData, request){console.log("error: "+errorData);}});
        }
      },

      delItemCallback: function(items, request){
        if (items.length == 1) {
          // Delete item
          CreateList.store.deleteItem(items[0]);
          CreateList.store.save({onComplete: CreateList.saveDone});
          dijit.byId("itemForm").reset();
        }
      },

      delItem: function () {
        var itemName = dijit.byId("itemForm").attr('value').name;
        if (itemName.length > 0) {
          CreateList.store.fetch({query:{name:itemName}, queryOptions:{ignoreCase: true}, onComplete: CreateList.delItemCallback});
        }
      },

      loadItemCallback: function(items, request){
        if (items.length == 1) {
          // Load to form item
          dijit.byId("itemForm").attr('value', {name:CreateList.store.getLabel(items[0]), qtty:CreateList.store.getValue(items[0], "qtty", ""),
          note:CreateList.store.getValue(items[0], "note", "")});
          dojo.byId("nameField").focus();
        }
      },

      loadItem: function(itemName) {
        if (itemName.length > 0) {
          CreateList.store.fetch({query:{name:itemName}, queryOptions:{ignoreCase: true}, onComplete: CreateList.loadItemCallback});
        }
      },

      makeXhr: function(items, request) {
        if (items.length == 0) {
          dojo.byId("errors").innerHTML = '<div class="errorlist">' + gettext('Shopping list is empty') + '</div>';
          dojo.byId("nameField").focus();
          return false;
        }
        // Disable Submit button
        dijit.byId("submitButton").attr('disabled', true);
        dojo.byId("errors").innerHTML = "";
        dojo.byId("status").innerHTML = gettext("Sending Your list to ") + dojo.byId("emailField").value + "...";
        var itemsForSend = [];
        for (var i = 0; i < items.length; i++) {
          var item = items[i];
          itemsForSend[i] = {name: CreateList.store.getLabel(item), qtty: CreateList.store.getValue(item, "qtty", ""),
          note: CreateList.store.getValue(item, "note", "")};
        }
        dojo.xhrPost ({
          url: '.',
          content: {  items: dojo.toJson(itemsForSend),
            title: dojo.byId("listNameField").value,
            mail_to: dojo.byId("emailField").value
          },
          //    handleAs: 'json-comment-filtered',
          // Loads this function if everything went ok
          load: function (data) {
            var respond = dojo.fromJson(data);
            //        console.log("redirect: " + respond["redirect_url"]);
            //        console.log("error: " + respond["errors"]);
            dojo.byId("status").innerHTML = "";
            dijit.byId("submitButton").attr('disabled', false);
            if (respond["errors"].length > 0) {
              dojo.byId("errors").innerHTML = respond["errors"];
              dojo.byId("emailField").focus();
            } else {
              dojo.byId("errors").innerHTML = "";
              //          console.log("redirect: " + respond["redirect_url"]);
              window.location = respond["redirect_url"];
            }
            //      console.log ('Data recieved: ' + );
          },
          // Call this function if an error happened
          error: function (error) {
            console.error ('Error: ', error);
          }
        });
      },

      submitForm: function() {
        if (dijit.byId("hdrForm").validate()) {
          if (dojo.byId("emailField").value.length == 0) {
            dojo.byId("errors").innerHTML = '<div class="errorlist">' + gettext('Please enter the email address.') + '</div>';
            dojo.byId("emailField").focus();
            return false;
          }
          CreateList.store.fetch({sort: [{attribute: "name"}], onComplete: CreateList.makeXhr});
          } else return false;
        },

        toTitleCase: function (str)	{
          return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
        },

        getvar: function() {return dojo.toJson(this.store)}
      };
    }
