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

}

ALREADY_INITIALIZED_BEFORE_UNLOAD = 0;
BEFORE_UNLOAD_FIRED = 1;

function resetBeforeUnload() {
   BEFORE_UNLOAD_FIRED = 0;
}

DearSantaManager.disableEnterKey = function(e) {
        var key;

        if(window.event) {
          key = window.event.keyCode;     //IE
        }
        else {
          key = e.which;     //firefox
        }

        if(key == 13) {
          return false;
        }
        else {
          return true;
        }
}

editingDetailId = '';
detailInfo = {};

DearSantaManager.prototype = {

    currentKeydown : {}, // key = text field, data = keycode
    baseUrl : '', // location of ${resource:dir('/")}
    loggedInUserId: '', // location of ${resource:dir('/")}
    saveInProgress: false,

    /**
     * This method is called after the page load is complete.
     */
    initialize : function(baseUrl, loggedInUserId) {
      this.baseUrl = baseUrl;
      this.loggedInUserId = loggedInUserId;
      this.saveInProgress = false;

      initializeMaskDialog();

      var timer = document.getElementById('dsCountdownTimer');
      if (timer) {
        var days = this.getDaysUntilXmas();
        var units = "days";
        if (days == 1) {
          units = "day";
        }
        timer.innerHTML = "<div style='text-align:center;font-size:18px'>" + days + "</div><div style='text-align:center; font-size: 15px'>" + units + "</div>";
      }

      this.initializeLetterEditor();
      this.initializeForgotPassword();

      $(window).bind("unload", function() {
        dearSantaManager.handleUnload()
      }); 

    },
    initializeForgotPassword : function() {
       dsLog("DearSantaManager - initializeForgotPassword() called");
       var input = Ext.get("recoverPasswordUsername") || Ext.get('resetPasswordPassword');
       if (input) {
           input.focus(30);
       }
    },

    beforeUnload : function(event) {
        var classThis = event.data.classThis;
	if (BEFORE_UNLOAD_FIRED == 0 && !classThis.buttonWasClicked) {
            //if (confirm("Are you sure you want to leave this page without saving or sending your letter?") == true) {
                //they pressed OK
            //} else {
                // they pressed Cancel
                //return false;
            //}
	    classThis.buttonWasClicked = true;
            BEFORE_UNLOAD_FIRED = 1;

            setTimeout("resetBeforeUnload()", "100");

            return "Changes to your letter will be lost if you leave this page.";
	}
    },

    initializeLetterEditor : function() {

        this.buttonWasClicked = false;


       dsLog("DearSantaManager - initializeLetterEditor() called");
        this.createLetterPageWasUnloaded = false;
        this.letterEditorLastSerializedParameters = undefined;
        this.wasLetterSaveClicked = false;
        this.alreadyAutosaved = false;
        this.timerRunCount = 0;

//        Ext.EventManager.on(window, 'unload', this.handleCreateLetterUnload, this);

        // If we're on the create letter page....
        if (Ext.get('isCreateLetterForm')) {
	    if (ALREADY_INITIALIZED_BEFORE_UNLOAD == 0) {
	    	$(window).bind("beforeunload", {classThis: this}, this.beforeUnload);
		ALREADY_INITIALIZED_BEFORE_UNLOAD = 1;
	    }

            //$(".useHint").hint();
            dsLog("DearSantaManager - isCreateLetterForm == true");

             $(".submitButton").click(function(event) {
                return dearSantaManager.submitButtonClicked();
             });

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


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

             $(".dsButtonSendLetter").bind('click', {classThis: this}, function(event) {
        	var classThis = event.data.classThis;
                event.preventDefault();
                $("#saveModeEl").val("send");

                mask("Please wait", "Sending your letter, please wait...");
        	classThis.buttonWasClicked = true;
                $("#letterForm").submit();
                return false;
             });
            
             $(".dsButtonSaveLetter").bind('click', {classThis: this}, function(event) {
        	var classThis = event.data.classThis;
                $("#saveModeEl").val("save");
                yesNoDialog("Are you sure?", "This will <b>not</b> send your letter to Santa, "
                        + "but instead it will save it so you "
                        + "can work on it later.<br/><br/>  Is this really "
                        + "what you want?", 
                        this, {
                            height: 200,
                            icon: 'ds-warning-icon',
                            yes: function() {
                                $("#saveModeEl").val("save");
        			classThis.buttonWasClicked = true;
                                mask("Please wait", "Saving your letter, please wait...");
                                $("#letterForm").submit();
                            }
                        });

                event.preventDefault();
                return false;
             });


             /*
             $(".dsLinkInput").CreateBubblePopup({
                 alwaysVisible: false,
                 mouseOut: 'show',

                 position : 'top', align    : 'center', tail : {align: 'center'},
                 innerHtml: 'Paste in a link to the item you want.',
                 innerHtmlStyle: { color:'#000000', 'text-align':'center' },
                 themeName:  'black',
                 themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
             });

             $(".dsImageLinkInput").CreateBubblePopup({
                 alwaysVisible: false,
                 mouseOut: 'show',

                 position : 'bottom', align    : 'center', tail : {align: 'center'},
                 innerHtml: 'Paste in a link to a picture of the item you want.',
                 innerHtmlStyle: { color:'#000000', 'text-align':'center' },
                 themeName:  'black',
                 themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
             });

             $("#letterContent").CreateBubblePopup({
                 alwaysVisible: false,
                 mouseOut: 'show',

                 position : 'top', align    : 'right', tail : {align: 'center'},
                 innerHtml: 'Type your message to <br>Santa here.',
                 innerHtmlStyle: { color:'#000000', 'text-align':'center' },
                 themeName:  'black',
                 themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
             });

             $("#letterContent").ShowBubblePopup();

             $(".dsEditDetailsButton").CreateBubblePopup({
                 position : 'left', align    : 'right', tail     : {align: 'center'},
                 distance : '5px',
                 innerHtml: 'Click here to show (or hide) a link<br/>to your item or a picture of it.',
                 innerHtmlStyle: { color:'#000000', 'text-align':'center' },
                 themeName:  'black',
                 themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
            });
            */

            // Put a hint by the lock to let people know what in the world it is.
            /*
             $(".dsLockIndicator").CreateBubblePopup({

                                    position : 'top',
                                    align    : 'center',
                                    innerHtml: 'The lock means this item can not be changed<br>' +
                                               'because you used it in a prior letter.',
                                    innerHtmlStyle: {
                                                        color:'#000000', 
                                                        'text-align':'center'
                                                    },
                                    themeName:  'black',
                                    themePath:  this.baseUrl + 'images/jquerybubblepopup-theme'
                                });
            */


            // Handle clicking on the "Edit details" button.
            $(".dsEditDetailsButton").bind('click', {classThis: this}, function(event) {
                var id = $(this).attr("id");
                var classThis = event.data.classThis;
                dsLog("DearSantaManager - details button clicked");
                editingDetailId = id;

                var parts = editingDetailId.split('_');
                var itemIndex = parseInt(parts[1]);
                var itemNumber = itemIndex;

                var details = detailInfo[id];
                var itemComment = "";
                var itemUrl = "";
                var imageUrl = "";
                if (details) {
                      itemComment = details.itemComment;
                      itemUrl = details.itemUrl;
                      imageUrl = details.imageUrl;
                }
                $("#itemComment").val(itemComment);
                $("#itemUrl").val(itemUrl);
                $("#imageUrl").val(imageUrl);

                var iconDiv = "#editDetailsIcon_" + itemIndex;
                if ($(iconDiv).hasClass("dsAreaClosed")) {
                    classThis.openDetailsForItem(itemNumber, true);
                } 
                else {
                    classThis.openDetailsForItem(itemNumber, false);
                }

                // now refocus on the original item they were editing
                $("#dsWish_" + itemIndex).focus();

            });

            var dt = new Ext.util.DelayedTask(function() {
				var lc = Ext.get("letterContent");
                lc.dom.focus();

                var isBasedOnDraft = Ext.get("is_based_on_draft");
                if (!isBasedOnDraft) {
                        lc.dom.select();
                }

			}, this);
            dt.delay(30);


            for (var f=1;f!=51;f++) {
              var inputField = Ext.get("dsWish_" + f);
              if (inputField) {
                  // NOTE: We can't use the keypress event, because it has a problem
                  // where the keys '&' and ")' show as the same key codes as the
                  // up and down arrows.
                  inputField.on("keydown", function(event, htmlEl) {
                      dsLog("keydown event");
                      var keyCode = event.getKey();
                      var parts = htmlEl.id.split('_');
                      var currentRow = parseInt(parts[1]);
                      if (keyCode == 38 && currentRow > 1) {   // 38 = up arrow
                          var prevRowId = "dsWishRow_" + (currentRow-1);
                          var prevRow = Ext.get(prevRowId);
                          var prevInput = Ext.get("dsWish_" + (currentRow-1));
			              if (prevRow) {
                              prevInput.focus(15);
            			  }
                      }

                      // 13 = enter, 40 = down arrow, 9=tab
                      if (keyCode == 13 || keyCode == 40 || (keyCode == 9 && !event.shiftKey)) {
                          var nextRowId = "dsWishRow_" + (currentRow+1);
                          var nextRow = Ext.get(nextRowId);
                          var nextInput = Ext.get("dsWish_" + (currentRow+1));
                          if (nextRow) {
                              nextRow.removeClass("dsHiddenComponent");
                              nextInput.focus(15);
                          }
                          if (keyCode == 13) {
                              event.stopEvent();
                              return false;
                          }
                      }
                  }, this)
              }
            }

            var task = {
                run: function(){
                    dsLog("Testing for autosave");
                    if (this.timerRunCount > 0) { // don't run when the page is initially loaded
                        if (this.createLetterPageWasUnloaded == false) {
                            this.saveLetterDraft("timedSave " + this.createLetterPageWasUnloaded);
                        }
                    }
                    this.timerRunCount++;
                },
                interval: (20 * 1000), //20 seconds
                scope: this
            }

            Ext.TaskMgr.start(task);

        }



    },

    /**
     * Mark our state to note that the user clicked "
     */
    submitButtonClicked: function() {

       dsLog("submitButtonClicked() called");
       var createInfo = this.createLetterFormParameters(true);
       var isValid = createInfo.isValid;
       if (isValid) {
          this.wasLetterSaveClicked = true;
          this.saveInProgress = true;
          this.hideValidationError();
          return true;
       }
       else {
          this.notifyOfValidationError();
          return false;
       }
    },

    saveLetterDraft : function(saveType) {
       dsLog("saveLetterDraft() called");

       // Don't bother saving a draft if a regular save is in progress.
       if (this.saveInProgress) {
            return;
       }
        var createInfo = this.createLetterFormParameters(false);
        var formParams = createInfo.formParams;
        formParams.saveType = saveType;

        var letterContent = formParams.letterContent;

        // If any data has changed since the last submit
        var formParamsEncoded = Ext.util.JSON.encode(formParams);
        if (formParamsEncoded != this.letterEditorLastSerializedParameters) {
            dsLog("Content changed, aa=" + this.alreadyAutosaved);
            dsLog("  NEW =" + Ext.util.JSON.encode(formParams));
            dsLog("  LAST=" + this.letterEditorLastSerializedParameters);
            dsLog("Autosave - Saving changes");
            if (this.alreadyAutosaved || this.letterHasInformationInIt()) {
                this.alreadyAutosaved = true;
                
                $.ajax({
                   url: this.baseUrl + "santaLetter/saveDraftJson",
                   context: this,
                   dataType: "json",
                   data: formParams,
                   traditional: true,
                   success: function(data,textStatus,request) {
                      checkAjaxResponseForExpiredSession(textStatus, "", {data: data}); 
                   },
                   error:function(req, textStatus, errorThrown) {
                      dsLog("Ajax response fail");
                      checkAjaxResponseForExpiredSession(textStatus, "", {}); 
                   }
               });

            }
            this.letterEditorLastSerializedParameters = formParamsEncoded;
        }
        else {
            dsLog("Autosave reported no changes");
        }

    },

    scopedHandleUnload : function() {
       dsLog("scopeHandleUnload() called");
        var isCreateLetter = Ext.get('isCreateLetterForm');
        if (isCreateLetter && !this.wasLetterSaveClicked) {

            this.createLetterPageWasUnloaded = true;

            this.saveLetterDraft("unload");
        }        
    },
    handleUnload : function() {
        dearSantaManager.scopedHandleUnload();

    }.createDelegate(this),
    letterHasInformationInIt: function() {
        var letterContent = Ext.get('letterContent').dom.value;
	    if (letterContent && letterContent.trim() != '') {
	        return true;
	    }
        for (var f=1;f!=51;f++) {
            var fieldName = "w_" + f;
            var fieldValue = Ext.get("dsWish_" + f).dom.value;
            if (fieldValue && fieldValue.trim() != '') {
		        return true;
            }
        }
	    return false;
      
    },
    createLetterFormParameters: function(doValidation) {
       dsLog("createLetterFormParameters() called");
        if (doValidation) {
            // hide all the error messages
            $(".dsLetterError").addClass("dsHiddenComponent");
        }
        var isValid = true;
        var letterContent = Ext.get('letterContent').dom.value;
        var formParams = {
            letterContent: letterContent,
            uid: this.loggedInUserId
        };

        // Now grab all the wish list items
        for (var f=1;f!=51;f++) {
            var thisFieldHadError = false;
            var fieldName = "w_" + f;
            var fieldValue = Ext.get("dsWish_" + f).dom.value;

            if (!fieldValue || fieldValue.trim() == '') {
                dsLog("processing item " + f + " skipped because it was blank");
                continue; // Assume items with a blank description are intended to be deleted.
            }
            dsLog("processing item " + f + " continued; value was '" + fieldValue + "'");

            formParams[fieldName] = fieldValue;

            // Add UUID to the request parameters.
            formParams["wuuid_" + f] = $("#wuuid_" + f).val();

            fieldName = "l_" + f;
            var fieldValue = $("#itemLink_" + f).val().trim();
            if (fieldValue && fieldValue != '') {
                if (doValidation && !isUrlValid(fieldValue)) {
                   $("#itemLinkError_" + f).removeClass("dsHiddenComponent");
                  isValid = false;
                  thisFieldHadError = true;
                }
                formParams[fieldName] = fieldValue;
            }

            fieldName = "il_" + f;
            var fieldValue = $("#itemImageLink_" + f).val().trim();
            if (fieldValue && fieldValue != '') {
                if (doValidation && !isUrlValid(fieldValue)) {
                   $("#itemImageLinkError_" + f).removeClass("dsHiddenComponent");
                   isValid = false;
                  thisFieldHadError = true;
                }
                formParams[fieldName] = fieldValue;
            }
            if (thisFieldHadError) {
                // If this field had an error, show the details section.
                this.openDetailsForItem(f, true);
            }
        }
        return {
            formParams: formParams,
            isValid: isValid
        };

    },
    openDetailsForItem : function(idx, openIt) {
       dsLog("openDetailsForItem() called");
        var iconDiv = "#editDetailsIcon_" + idx;
        if (openIt) { // open it
            $("#dsWishRowDetail_" + idx).show();
            //$("#dsWishRowDetail_" + idx).effect( 'slide', {direction: 'up'});
            $(iconDiv).removeClass("dsAreaClosed");
        }
        else { // close it
            $("#dsWishRowDetail_" + idx).hide();
            //$("#dsWishRowDetail_" + idx).hide( 'slide', {direction: 'up'});
            $(iconDiv).addClass("dsAreaClosed");
        }
    },

    notifyOfValidationError : function() {
        $("#dsValidationErrorMessage").effect( 'slide', {direction: 'up'});
    },
    hideValidationError : function() {
        $("#dsValidationErrorMessage").hide();
    },
    
    getDaysUntilXmas : function() {
       dsLog("getDaysUntilXmas() called");
      var oneMinute = 60 * 1000
      var oneHour = oneMinute * 60
      var oneDay = oneHour * 24
      var today = new Date()
      var nextXmas = new Date()
      nextXmas.setMonth(11)
      nextXmas.setDate(25)
      if (today.getMonth() == 11 && today.getDate() > 25) {
        nextXmas.setFullYear(nextXmas.getFullYear() + 1)
      }
      var diff = nextXmas.getTime() - today.getTime()
      diff = Math.floor(diff / oneDay)
      return diff
    }

}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}




