/**
 * Class that does dynamic actions when editing the wish list
 */
WishListShare = function() {

}

WishListShare.staticFunction = function(e) {
   // 
}

maxId = 0;
enableGridAnimateAdd = false;

WishListShare.prototype = {
    wishListController: '',
    baseUrl : '', // location of ${resource:dir('/")}
    wishListIds: [], 

    /**
     * This method is called after the page load is complete
     * to initialize the dialog, other widgets, and event
     * handlers.
     * @param baseUrl - base URL of web app
     */
    initialize : function(controller, baseUrl) {
        this.wishListController = controller;
        this.baseUrl = baseUrl;

        // Create the combo box
        $("#combobox").combobox();
        $("#myComboBox").css('width', '190px');

        // unclear if this is really needed anymore
        //$(".shareDeleteButton").button({
         //   icons: {
          //      primary: "ds-delete-button-icon"
           //     //secondary: "ui-icon-triangle-1-s"
            //},
            //text: false
        //});

        this._createGrid();
        this._createDialog();

    },

    // Show the share dialog
    // @param wishListIds - Array of wish list Ids
    show : function(wishListIds) {
      this._clear();
      this.wishListIds = wishListIds;
   
      var classThis = this; 
      // Look up current sharing for the wish lists 
      $.ajax({
             url: this.baseUrl + "wishList/existingSharingJson",
             async: false,
             context: this,
             dataType: "json",
             data: {
                wish_list_ids: this.wishListIds.join(",")
             },
             success: function(data,textStatus,request) {
                dsLog("Ajax response success");
                if ( isAjaxError(data, textStatus, request) ) { 
                    showAjaxError("Sorry, could not load sharing information.  Please try again later",
                        {data: data, textStatus: textStatus, request: request});
                }
                else {
                    classThis._loadDataIntoGrid(data);
                }
             },
             error:function(req, textStatus, errorThrown) {
                dsLog("Ajax response fail");
                showAjaxError("Sorry, could not load sharing information.  Please try again later",
                    { request: req, textStatus: textStatus, errorThrown: errorThrown });
             }
      });
    },
    /**
     *  Load the AJAX response into the grid.
     */
    _loadDataIntoGrid : function(data) {

        // Reset the list of wish list Ids to only those that the user has access to.
        this.wishListIds = data.wishListIds;

        var editingSingleList  = (this.wishListIds.length == 1);

        if (editingSingleList) {
            $("#dsShareDialogTitle").text("Edit Wish List Sharing");
        }
        else {
            $("#dsShareDialogTitle").text("Edit Wish List Sharing (" + this.wishListIds.length + " lists )");
        }

        var hideShareColumn = editingSingleList ;

        if (hideShareColumn) {
            jQuery("#shareTable").jqGrid ('hideCol', 'shareMode');
            jQuery("#shareTable").jqGrid ('setGridWidth', 290);
        }
        else {
            jQuery("#shareTable").jqGrid ('showCol', 'shareMode');
            jQuery("#shareTable").jqGrid ('setGridWidth', 380);
        }
     
        // load the data into the grid
        // ---------------------------
        enableGridAnimateAdd = false;

        var gridData = data.gridData;
        var len=gridData.length;
        for (var i=0;i<len;i++) {
            this._addRowToGrid(gridData[i]["email"], gridData[i]["shareMode"], false);
        }

        enableGridAnimateAdd = true;

        // finally, show the dialog
        $("#shareDialogEl").dialog('open');
        if (hideShareColumn) {
            $("#shareDialogEl").parent().css("width", 340);
        } else {
            $("#shareDialogEl").parent().css("width", 430);
        }
    },
    _getShareDataFromGrid : function() {
        var shareData = [];
        var rows = jQuery("#shareTable").getDataIDs();
        for (var i=0;i!=rows.length;i++) {
            var id = rows[i];
            var objRowData = jQuery("#shareTable").getRowData(id);

            var smSelector = "#shareMode_" + (i+1);
            var shareModeSelection = $(smSelector).val();
            if (!shareModeSelection || shareModeSelection == "") {
               shareModeSelection = "all";
            }
            shareData.push({
                email: objRowData["email"],
                shareMode: shareModeSelection  // NOT objRowData['shareMode'], that's the widget
            });
        }
        return shareData;
    },
    _handleSave : function() {

        mask("Please wait...", "Saving, please wait...", {});

        var shareData = this._getShareDataFromGrid();

        var shareDataEncoded = Ext.encode(shareData);
        $.ajax({
             url: this.baseUrl + "wishList/saveShareJson",
             async: false,
             dataType: "json",
             data: {
                share_data: shareDataEncoded,
                wish_list_ids: this.wishListIds.join(",")
             },
             success: function(data,textStatus, request) {
                unmask();
                if ( isAjaxError(data, textStatus, request) ) { 
                    showAjaxError("Sorry, updating sharing failed.  Please try again later.",
                        {data: data, textStatus: textStatus, request: request});
                }
             },
             error:function(req, textStatus, errorThrown) {
                unmask();
                showAjaxError("Sorry, updating sharing failed.  Please try again later.",
                    { request: req, textStatus: textStatus, errorThrown: errorThrown });
             }
         });
    },

    /**
     *  Create the grid
     *  ________________________________________________
     */
    _createGrid : function() {

      var shareColNames = ['ID', 'Email', 'Can access', ' ' ];
      var shareColModel= [
          {name:'id',index:'id', width:60, sorttype:"int", hidden: true},
          {name:'email',index:'email', width:270},
          {name:'shareMode',index:'shareMode', align: "center", width:90},
          {name:'buttonTxt',index:'buttonTxt', width:20, align: "center"}
      ];

      jQuery("#shareTable").jqGrid({
              datatype: "local",
              height: 150,
              hidegrid: false,
              hoverrows: false,
              colNames: shareColNames,
              colModel: shareColModel,
              multiselect: false,
              caption: "Shared to",
              afterInsertRow: function(rowid, rowdata, rowelem) {
                  $(".ui-jqgrid-bdiv").scrollTo("100%", {duration: 500});
  
                  // Highlight the newly added row.
                  if (enableGridAnimateAdd) {
                      $("#" + rowid + " td").animate({
                          backgroundColor: "#FDF5CE" // orangeish color
                      }, 300,"linear",
                          function() {
                              $("#" + rowid + " td").animate({
                                  backgroundColor: "white"
                              },700);
                          }
                      );
                  }
  
              },
              beforeSelectRow : function() {
                  // don't allow selection within this grid.
                  return false;
              },
              gridComplete: function(){ 
                  // Hide the header on the grid
                  // $('#shareTable > .ui-jqgrid-titlebar').hide();
                  setupDeleteButtons();
  
                  // Change the text align of the email column header to be left aligned.
                  //jQuery("#shareTable").jqGrid ('setLabel', 1, '', {'text-align':'left'});
              }
       });  // end create the grid`

        // Handle clicking "Add" button 
        // ----------------------------
        $('#shareAddButton').bind('click', { classThis: this }, function(event) {
            var classThis = event.data.classThis;
            var comboValue = $("#emailComboWrapperEl input").val();
            classThis._addRowToGrid(comboValue, "all", true);
            // $(".ui-jqgrid-bdiv").scrollTo("100%", {duration:500});
        });

        // Handle pressing enter
        // ----------------------------
        $("#emailComboWrapperEl input").bind('keypress', { classThis: this }, function(event) {
            var classThis = event.data.classThis;
            if(event.keyCode == 13) {
                var comboValue = $("#emailComboWrapperEl input").val();
                classThis._addRowToGrid(comboValue, "all", true);
            }
        });

    },
    /**
     *  Create the dialog
     *  ________________________________________________
     */
    _createDialog : function() {
      var title = "Share Wish List";

      var tmpThis = this;
        $("#shareDialogEl").dialog({
			autoOpen: false,
            modal: true,
            resizable: false,
            minWidth: 340,
            width:    430,
			title: '<div id="dsShareDialogTitle" class="ds-group-icon"> ' + title + '</div>',
            open: function(event,ui) {
                // $(".useHint").hint();
            },
            buttons: {
                "Save": function() {
                    var comboValue = $("#emailComboWrapperEl input").val();
                    if (comboValue && comboValue.trim() != '') {
                        var shareDialog = $(this);
                        yesNoDialog("Save changes?", "You have one email address (" + comboValue +") that"
                            + " you have not added yet.  Do you want to add it prior to saving?"
                            , tmpThis, {
                                height: 160,
                                icon: 'ds-group-icon',
                                yes: function() {
                                    var comboValue = $("#emailComboWrapperEl input").val();
                                    if (this._addRowToGrid(comboValue, "all", true)) {
                                        shareDialog.dialog( "close" );
                                        tmpThis._handleSave();
                                    }
                                },
                                no : function() {
                                    shareDialog.dialog( "close" );
                                    tmpThis._handleSave();
                                }
                            });
                    }
                    else {
                        $( this ).dialog( "close" );
                        tmpThis._handleSave();
                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            }
		});
    },
    /**
     *  Clear all settings
     */
    _clear : function() {
        maxId = 0;
        clearComboBox();

        // clear the grid
        jQuery("#shareTable").jqGrid('clearGridData');
    },
    /**
     *  Add a row of data to the grid
     */
    _addRowToGrid : function(email, shareMode, userCreated) {
        var didAdd = false;
        if (email && email.trim() != "") {
            email = email.trim();
            if (!isEmailValid(email)) {
               showShareValidationError('Email address is invalid.</div>'); 
            }
            else {
                if (getEmailRowNumber(email) == -1) {
                    maxId++;
                    var someSelected = (shareMode == "some");

                    var shareModeHtml =  '<input type="hidden" id="shareMode_' + maxId + '" value="all"></input>All lists';
                    if (someSelected) {
                        var shareModeHtml =  '<select class="dsShareModeSelect" id="shareMode_' 
                                + maxId + '"><option value="all">All lists</option><option value="some" selected="selected" '
                                + '>Some lists</option></select>';
                    }
                    jQuery("#shareTable").jqGrid('addRowData',maxId,{
                        id: maxId,
                        email: email,
                        shareMode: shareModeHtml,
                        buttonTxt:'<div id="delRow_' + maxId + '" class="shareEmailDelete"></div>'
                    });
                    didAdd = true;

                    if (userCreated) {
                        clearComboBox();
                    }
                    setupDeleteButtons();
                }
                else {
                    showShareValidationError("That email is already in the list."); 
                }
            }
        }
        return didAdd;
    }
}



setupDeleteButtons = function() {
        //$(".shareEmailDelete").button({
        //        icons: {
        //            primary: "ds-delete-button-icon"
        //            //secondary: "ui-icon-triangle-1-s"
        //        },
        //        text: false
        //});

       $(".shareEmailDelete").click(function() {
          var id = $(this).attr("id");
          var items = id.split("_",2);
          var rowId = items[1];
          $("#" + rowId + " td").css("background-color", "red");
          $("#" + rowId + " td").animate(
            { backgroundColor: "white" },200,
            function() {
                    jQuery("#shareTable").jqGrid('delRowData',rowId);
            }
          );

       });
}


showShareValidationError = function(msg) {
   $("#validationError").html('<div style="margin-left: 0px; margin-right: 20px;" class="message">' + msg + '</div>'); 
   $("#validationError").show();
   $("#validationError").delay(1000).fadeOut('slow');
 
}

clearComboBox = function()  {
    $("#emailComboWrapperEl input").val("");
}

getAllEmails = function() {
    var all_emails = "";
    var rows = jQuery("#shareTable").getDataIDs();
    for (var i=0;i!=rows.length;i++) {
        var id = rows[i];
        var objRowData = jQuery("#shareTable").getRowData(id);
        if (i!=0) {
            all_emails = all_emails + ",";
        }
        all_emails = all_emails + objRowData["email"];
    }
    return all_emails;
}

getEmailRowNumber = function(email) {
    var rows = jQuery("#shareTable").getDataIDs();
    for (var i=0;i!=rows.length;i++) {
        var id = rows[i];
        var objRowData = jQuery("#shareTable").getRowData(id);
        if (objRowData["email"] == email) {
            return i;
        }
    }
    return -1;
}



