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

}

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

maxId = 0;
gridFullyLoaded = false;


WishList.prototype = {

    baseUrl : '', // location of ${resource:dir('/")}
    wishListIds: [], 
    selectedCommentId: null, 
    shareDialog: null,
    wishListComment: null,
    wishListWillGift: null,
    selectAllChecked : false,
    currentlyAdding: false,
    lastWishListUpdateTime: 1,
    dsIsFirstFocus : true,

    /**
     * This method is called after the page load is complete.
     * @param baseUrl     = base url of web site
     * @param wishListIds = array of wish list ids
     */
    initialize : function(baseUrl, wishListIds) {
      this.baseUrl = baseUrl;
      this.wishListIds = wishListIds;

      var d = new Date();
      this.lastWishListUpdateTime = d.getTime();

      this.shareDialog = new WishListShare();
      this.shareDialog.initialize(this,baseUrl);

      this.wishListComment = new WishListComment();
      this.wishListComment.initialize(this,baseUrl);

      this.wishListWillGift= new WishListWillGift();
      this.wishListWillGift.initialize(this,baseUrl);

      this.isOnListPage = ($("#isOnWishListPage").length > 0);

      $(".dsButtonSelectAll").button({
            text: true
      });

      // Do actions common to both list and show pages
      $("#shareButtonEl").button({
            icons: {
                primary: "ds-icon-group"
                //secondary: "ui-icon-triangle-1-s"
            },
            text: true
      });

      $(".dsButtonGift").button({
            icons: {
                primary: "ds-icon-gift"
                //secondary: "ui-icon-triangle-1-s"
            },
            text: true
      });


/* 
      $(".addCommentButton").button({
            icons: {
                primary: "ds-add-comment"
                //secondary: "ui-icon-triangle-1-s"
            },
            text: true
      });
*/
	 

      $(".dsButton").button({
            text: true
      });

      if (this.isOnListPage) {
        dsLog("initializing list page");
        this.initializeListPage();
      }
      else {
        dsLog("initializing show page");
        this.initializeShowPage();
      }

    },
    enableSelectAllHandler : function() {
      $("#selectAll").bind('click', { classThis: this }, function(event) {
           dsLog("checkbox clicked");
           var classThis = event.data.classThis;
           event.stopImmediatePropagation();
           classThis.selectAllButtonChanged();
           return true;
      });

      $(".dsButtonSelectAll").bind('click', { classThis: this }, function(event) {
          dsLog("button clicked");
          var classThis = event.data.classThis;

          /*
          if ($("#selectAll").is(':checked')) {
             $("#selectAll").attr('checked', false);
          }
          else {
             $("#selectAll").attr('checked', true); 
          }
          */
          classThis.selectAllButtonChanged();
          return true;
      });

    },

    reloadWishList : function (event) {
     //dsLog("SKIPPING Reloading wish list...");
     //return;

     var classThis = event.data.classThis;
     if (classThis.dsIsFirstFocus) {
        classThis.dsIsFirstFocus = false;
     }
     else {
       var d = new Date();
       var timeNow = d.getTime();
       var sinceLast = timeNow - classThis.lastWishListUpdateTime;
       if (sinceLast < 3000) {
            dsLog("Ignoring wish list update, one just happened " + sinceLast + " ms ago.");
            return;
       }
       classThis.lastWishListUpdateTime = timeNow;
       mask("Please wait", "Updating list, please wait...");
       dsLog("----  Reloading wish list... ------");
       $.ajax({
             url: classThis.baseUrl + "wishList/allItemsJson",
             async: false,
             context: classThis,
             dataType: "json",
             data: {
                id : classThis.wishListIds[0]
             },
             success: function(data,textStatus,request) {
                dsLog("wishList/allItemsJson - Ajax response success");
                if (data['success'] == 'false' || data['success'] == false) {
                    dsLog("WARN: allItemsJson did not return success.");
                    unmask();
                    // ignore errors
                }
                else {
                    dsLog("Received allItemsJosn JSON.");
                    //dsLog("Received allItemsJosn JSON, HTML is " + data.html);
                    $("#dsItemsRendered").html(data.html);
                    unmask();
                    this.initializeShowPage();
                }
             },
             error:function(req, textStatus, errorThrown) {
                dsLog("WARNING allItemsJson failed: " + textStatus);
                // We'll ignore errors; this is an auto-reload case
                unmask();
             }
      });
     }
    },

    disableSelectAllHandler : function() {
      $("#selectAll").unbind('click');
      $(".dsButtonSelectAll").unbind('click');

    },
    initializeListPage : function() {
      dsLog(" (in initializeListPage())\n");
    
      this.enableSelectAllHandler();

      // Handle clicking on the share button 
      $('#shareButtonEl').bind('click', { classThis: this }, function(event) {
        var classThis = event.data.classThis;

        var selectedWishListIds = [];
        
        // Find all the checked wish list ids
        $(".dsItemCheckbox:checked").each(function() {
            var wishListId = extractId($(this).attr("id"));
            selectedWishListIds.push(wishListId);
        });

        if (selectedWishListIds.length == 0) {
            showWarningDialog("Please select a wish list.", 
                        "Click the check box to the left of the wish list <br/>"
                    +   "(or lists) that you want to work with.");
        }
        else {
            // Open the share dialog with the selected wish list ids
            classThis.shareDialog.show(selectedWishListIds);
        }
      });
    },
    selectAllButtonChanged : function() {
        dsLog("selectAllButtonChanged");
         
        this.disableSelectAllHandler();
        if (this.selectAllChecked) {
            dsLog(" - OFF");
            $(".dsItemCheckbox").attr('checked', false);
            this.selectAllChecked = false;
             $("#selectAll").attr('checked', false);
        }
        else {
            dsLog(" - ON");
            $(".dsItemCheckbox").attr('checked', true);
            this.selectAllChecked = true;
             $("#selectAll").attr('checked', true);
        }
        this.enableSelectAllHandler();
    },
    initializeShowPage : function() {

       // Handle clicking on the share button 
       $('#shareButtonEl').unbind('click');
       $('#shareButtonEl').bind('click', { classThis: this }, function(event) {
           var classThis = event.data.classThis;
           classThis.shareDialog.show(classThis.wishListIds);
       });

       //$(".delCommentDiv").fadeTo(100,0.4);

        /* 
       $(".wldCommentTable").hover(
          function() {
             var commentId= extractId($(this).attr("id"));
             $("#delCommentDiv_" + commentId).fadeTo(400, 1.0);
          },
          function() {
             var commentId= extractId($(this).attr("id"));
             $("#delCommentDiv_" + commentId).fadeTo(400, 0.4);
          }
        );
        */

       $('.dsLocalTime').each(function(index,element) {
            var contents = $(element).text();
            dsLog("Date as a number is " + contents);
            var myDate = new Date( Number(contents) );
            // see http://blog.stevenlevithan.com/archives/date-time-format
            var dateFormat = myDate.format("mmm d, yyyy");
            var timeFormat = myDate.format("h:MM:ss TT");
            $(element).replaceWith('<span id="dsLocalizedTime">' + dateFormat + " at " + timeFormat + "</span>");
        });

       $('.dsAddComment').unbind('click');
       $('.dsAddComment').bind('click', { classThis: this }, function(event) {
           var classThis = event.data.classThis;
           var wishListId = extractId($(this).attr("id"));
           classThis.wishListComment.showAddDialog(wishListId);
           return false;
        });

       $('.dsDeleteItem').unbind('click');
       $('.dsDeleteItem').bind('click', { classThis: this }, function(event) {
           var classThis = event.data.classThis;
           var wishListItemId = extractId($(this).attr("id"));
           yesNoDialog("Are you sure?", "Are you sure you want to delete this wish?", classThis,
            {
                yes: function() {
                  classThis.deleteItem(wishListItemId);
                }
            });
           return false;
        });

       $('.dsDeleteComment').unbind('click');
       $('.dsDeleteComment').bind('click', { classThis: this }, function(event) {
           var classThis = event.data.classThis;
           classThis.selectedCommentId = extractId($(this).attr("id"));

           yesNoDialog("Are you sure?", "Are you sure you want to delete this item?", classThis,
            {
                yes: classThis.handleDeleteCommentClicked
            });
           return false;
       });


        // Handle pressing enter
        // ----------------------------
        $('#wlName').unbind('click');
        $("#wlName").bind('keypress', { classThis: this }, function(event) {
            var classThis = event.data.classThis; //wlName CR
            if(classThis.currentlyAdding == false && event.keyCode == 13) {
                classThis.currentlyAdding = true;
                var wishListId = extractId($(".dsAddItem").attr("id"));
                classThis.handleAddItem(wishListId);
            }
        });

       $('.dsAddItem').unbind('click');
       $('.dsAddItem').bind('click', { classThis: this }, function(event) {
            var wishListId = extractId($(this).attr("id"));
            var classThis = event.data.classThis; //dsAddItem
            classThis.handleAddItem(wishListId);
       });
    

       $('.dsAddWillGift').unbind('click');
       $('.dsAddWillGift').bind('click', { classThis: this }, function(event) {
           var classThis = event.data.classThis; //dsAddWillGIft
           var wishListId = extractId($(this).attr("id"));
           classThis.wishListWillGift.showAddDialog(wishListId);
           return false;
        });

       $(".dsGiveGiftBubble").RemoveBubblePopup();
       $(".dsGiveGiftBubble").CreateBubblePopup({

                                    position : 'left',
                                    align    : 'center',
                                    innerHtml: 'Click this to indicate you plan to give this gift.<br/><br/>' +
                                               'This button does not actually buy the gift -- that<br/>' +
                                               'part is up to you.  This just lets other people<br/>' +
                                               'with whom the list has been shared know that <br/>' +
                                               'you have called dibs on it!',
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });

       $(".dsDeleteItemBubble").RemoveBubblePopup();
       $(".dsDeleteItemBubble").CreateBubblePopup({

                                    position : 'left',
                                    align    : 'center',
                                    distance : 15,
                                    innerHtml: 'Delete this wish from the list.<br/> '  
                                             , 
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });


       $(".dsAddCommentNotMyList").RemoveBubblePopup();
       $(".dsAddCommentNotMyList").CreateBubblePopup({
                                    position : 'left',
                                    align    : 'center',
                                    innerHtml: 'Add a comment about this gift.<br/><br/>' +
                                               'Note: Comments by gift-givers are never visible to <br/>' +
                                               'the person you are giving the gift to.  Only other <br/>' +
                                               'gift givers can see these secret comments.',
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });

       $(".dsAddCommentMyList").RemoveBubblePopup();
       $(".dsAddCommentMyList").CreateBubblePopup({
                                    position : 'left',
                                    align    : 'center',
                                    innerHtml: 'Add a comment to tell Santa more about this wish.',
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });

       $(".dsGotIt").RemoveBubblePopup();
       $(".dsGotIt").CreateBubblePopup({

                                    position : 'top',
                                    align    : 'center',
                                    innerHtml: 'This item is checked off the list!<br/> '  +
                                               'That means someone has already promised to give them this gift. ' 
                                             , 
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });


      /*
       $(".dsDeleteComment").RemoveBubblePopup();
       $(".dsDeleteComment").CreateBubblePopup({

                                    position : 'top',
                                    align    : 'center',
                                    distance : 15,
                                    innerHtml: 'Delete this comment.<br/> '  
                                             , 
                                    innerHtmlStyle: {
                                                        color:'#000000',
                                                        'text-align':'left'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });
        */


        // reset the event handlers for this too
        this.wishListWillGift.initilizeEventHandlers();
    },
    handleDeleteCommentClicked: function() {
        this.wishListComment.deleteComment(this.selectedCommentId);
    },
    deleteItem: function(wishListItemId) {
       //mask("Please wait", "Deleting item, please wait...");
       $.ajax({
             url: this.baseUrl + "wishList/deleteItemJson",
             async: false,
             context: this,
             dataType: "json",
             data: {
                wish_list_item_id: wishListItemId
             },
             success: function(data,textStatus,request) {
                //unmask();
                if ( isAjaxError(data, textStatus, request) ) {
                    dsLog("Ajax response fail");
                    showAjaxError("Sorry, could not delete item.  Please try again later",
                        {data: data, textStatus: textStatus, request: request});
                }
                else {
                    dsLog("Ajax response success");
                    //location.reload(true);
                    var id = data.wishListItemId;
                    $("#wishListItem_" + id).remove(); 
                }
             },
             error:function(req, textStatus, errorThrown) {
                //unmask();
                dsLog("Ajax response fail");
                showAjaxError("Sorry, could not delete item. Please try again later",
                    { request: req, textStatus: textStatus, errorThrown: errorThrown });
             }
      });

    },
    addItem: function(wishListId, quantity, name) {
       //mask("Please wait", "Adding item, please wait...");
       var classThis = this;
       $.ajax({
             url: this.baseUrl + "wishList/addItemJson",
             async: false,
             context: this,
             dataType: "json",
             data: {
                wish_list_id : wishListId,
                quantity: quantity,
                name: name
             },
             success: function(data,textStatus,request) {
                dsLog("Ajax response success");
                if (data['success'] == 'false' || data['success'] == false) {
                    //unmask();
                    if (data['reason'] == 'Maximum # of wishes exceeded') {
                        alertDialog("Too many wishes", 
                            "Sorry, you can only have 50 wishes in your list at this time.",
                            classThis, 
                            { height: 170,
                              width: 300, 
                              close : function() { 
                                    unmask();
                              }
                            });
                    }
                    else {
                        if ( isAjaxError(data, textStatus, request) ) {
                            showAjaxError("Sorry, could not add item.  Please try again later",
                                {data: data, textStatus: textStatus, request: request});
                        }
                    }
                }
                else {
                    // Insert the newly added element into the document
                    $("#dsItemsRendered").append(data.html);
                    $("#wlName").val("");
                    this.initializeShowPage();
                    //location.reload(true);
                }
                this.currentlyAdding = false;
             },
             error:function(req, textStatus, errorThrown) {
                unmask();
                dsLog("Ajax response fail");
                showAjaxError("Sorry, could not add item.  Please try again later",
                    { request: req, textStatus: textStatus, errorThrown: errorThrown });
                this.currentlyAdding = false;
             }
      });
    },
    handleAddItem: function(wishListId) {
           var quantity = $("#needQty").val();
           var name = $("#wlName").val();
           if (name && name.trim() != "") {
                this.addItem(wishListId, quantity, name);
           }
           return false;
   }
}


