/* ################################################################# */
/*                                                                   */
/*  TITLE:        NBC_CONTENT.JS                                      */
/*  LAST UPDATED: 9/18/2009                                          */
/*  UPDATED BY:   Nekoro Gloster                                    */
/*                                                                   */
/*  NAMESPACE: NBC_Content                                            */
/*    mmt (instance of this class)                                   */
/*                                                                   */
/*  PREREQUISTES/DEPENDENCY:                                         */
/*    user                                                           */
/*    nbc                                                            */
/*    U.log                                                          */
/*    NBC_EventManager                                               */
/*                                                                   */
/*  @release 2009-10-29 nekoro                                      */
/*                                                                   */
/* ################################################################# */
var NBC_Content = function() {};

NBC_Content.prototype.currCatIdx = 0;
NBC_Content.prototype.currMomIdx = 0;
NBC_Content.prototype.currMom;
NBC_Content.prototype.momArr;
NBC_Content.prototype.hasMoments;
NBC_Content.prototype.isValid = true;
NBC_Content.prototype.config;

NBC_Content.prototype.nullMoment = {
  id: '', detail: '', rating: '', author: '', category: '', date: '', 
  commentCount: ''
};

NBC_Content.prototype.countClicks = {
	countCancel: '',
	countSubmit: ''
};

NBC_Content.prototype.cc;
NBC_Content.prototype.init = function(options) {
  var self = this;
  if (!options) {
    throw new Error("Invalid initialization for content js.")
  }
  self.config = options;
  NBC_Content.prototype.config = self.config;
  
  $(document).ready( function() {
    
    /* FOR EDITORS, SHOW EDIT LINK */
    if (user.isEditor()) {
      $("#momentAdmin").show();
    }
        
    $("#hideThankYou").click(function() {
	    $("#momentThankYou").fadeOut("fast");
	    $("#inlineMomentForm").css("opacity", 1);
	    $("#inlineMomentForm").css("display", "block");
	    $("#momentCollTxtBox_area").removeClass("inlineTextAreaOpen");
	    $("#momentCollTxtBox_area").addClass("inlineTextAreaClosed");
	    $("#postMomentForm").fadeIn("fast");
    });
    
    /* ANONYMOUS USER CHECKED / UNCHECKED CHANGE USER IN PREVIEW */
    $("#anonymous_button").click( function() {
      if ($("#anonymous_button").attr("checked")) {
        $("#momentPreviewUserName").text("Anonymous");
        $("#momentPublish").hide();
        U.log("Preview says: anonymous_user");
      } else {
        $("#momentPreviewUserName").text(user.userName);
        U.log("Preview says: Username");
        $("#momentPublish").show();
      }
    });

    /* MOMENT CONTROLS */
    $("#mom_nav_previous").click( function() {
      self.displayNextMoment({goToPrev:true});
    });
    $("#mom_nav_next").click( function() {
      self.displayNextMoment({goToNext:true});
    });
    $("#momentDetail, .momentComments a").click( function() {
      self.goToMomentAgg();
    });
    $("#momentAuthorLink").click( function() {
      self.goToUserProfile();
    });
    // takes user back to moment module after posting
    $("#momentBackToMainId").click( function() {
      self.backToMain();
    });
    // hides the image upload
    $("#momentImageUploadCancel").click( function() {
      $('#photoUploadLayer').fadeOut();
      $('#momentImageUploadBtn').hide();
    });	
    // brings/hides add
    $('#addMoment, #momentHadAHeader').click( function() {
      nbc.submissionType  = "moment";
      G.doPixelTracking(35);	
      self.countClicks.countCancel = "0";
      self.countClicks.countSubmit = "0";

      NBC_EventManager.fire("moment.entry.start"); 
    });

  });

  /* INIT CHAR COUNTER */
  $(document).ready( function() {
    self.cc = new NBC_CharCounter();
    self.cc.init( {
      objName : "mmt.cc",
      maxLength : 550,
      textAreaId : 'momentCollTxtBox_area',
      charLimitFieldId : 'momentCharLimitTxt',
      charLimitTextFieldId : 'momentCharLimit',
      charMaxFieldId : 'momentCharMax'
    });    
  });

  /* INIT COUNTERS FOR CANCEL AND SUBMIT */
  $(document).ready( function() {
	  self.countClicks.countCancel = "0";
	  self.countClicks.countSubmit = "0";
  });

  /** EXPANDED MODE */
  $(document).ready(function() {
    /* USER CLICKING CANCEL LINK */

    /* MOMENT FORM SUBMIT */
    $("#momentPostButton").click( function() {
      NBC_Content.prototype.validate();
      if( NBC_Content.prototype.isValid ){
        self.postContent();   
      } else {
        var msg = document.getElementById("requiredMsg");
        msg.style.visibility = "visible";
      }
      return false;
    });	    
  });

  /* MODULE DISPLAY */
  $(document).ready( function() {
    //flips the drop down arrow and shows it on main moment layer
    $("#dropDownClick").click( function() {
      if ($("#dropDownList").is(":hidden")) {
        $("#dropDownList").slideDown("fast");
        $("#momentDropDownArrow").removeClass('dropDownArrow');
        $("#momentDropDownArrow").addClass('dropUpArrow');
        $("#dropDownList").addClass("momentDDPosition");
      } else {
        $("#dropDownList").slideUp("fast");
        $("#momentDropDownArrow").removeClass('dropUpArrow');
        $("#momentDropDownArrow").addClass('dropDownArrow');
      }
    });

    // flips the drop down arrow and shows it on add moment layer
    $("#dropDownAddClick").click( function() {
      if ($("#dropDownList").is(":hidden")) {
        $("#dropDownList").removeClass("momentDDPosition");
        $("#dropDownList").addClass("momentADDPosition");
        $("#dropDownList").slideDown("fast");
        $("#momentDropDownArrow").removeClass('dropDownArrow');
        $("#momentDropDownArrow").addClass('dropUpArrow');
      } else {
        $("#dropDownList").slideUp("fast");
        $("#momentDropDownArrow").removeClass('dropUpArrow');
        $("#momentDropDownArrow").addClass('dropDownArrow');
      }
    });

    // flips the drop down arrow and shows it on add moment layer from
    // inside text area.
    $("#momentChangeCategory").click( function() {
      if ($("#dropDownList").is(":hidden")) {
        $("#dropDownList").removeClass("momentDDPosition");
        $("#dropDownList").addClass("momentADDPosition");
        $("#dropDownList").slideDown("fast");
        $("#momentDropDownArrow").removeClass('dropDownArrow');
        $("#momentDropDownArrow").addClass('dropUpArrow');
      } else {
        $("#dropDownList").slideUp("fast");
        $("#momentDropDownArrow").removeClass('dropUpArrow');
        $("#momentDropDownArrow").addClass('dropDownArrow');
      }
    });

    // flips the drop down arrow and shows it on add moment layer from
    // inside text area.
    $("#momentChangeCategoryLink").click( function() {
      if ($("#dropDownList").is(":hidden")) {
        $("#dropDownList").removeClass("momentDDPosition");
        $("#dropDownList").addClass("momentADDPosition");
        $("#dropDownList").slideDown("fast");
        $("#momentDropDownArrow").removeClass('dropDownArrow');
        $("#momentDropDownArrow").addClass('dropUpArrow');
      } else {
        $("#dropDownList").slideUp("fast");
        $("#momentDropDownArrow").removeClass('dropUpArrow');
        $("#momentDropDownArrow").addClass('dropDownArrow');
      }
    });

    // flips the arrow back up after a user selects a different category
    $("#dropDownList a").click( function() {
      $("#dropDownList").hide();
      $("#momentDropDownArrow").removeClass('dropUpArrow');
      $("#momentDropDownArrow").addClass('dropDownArrow');
    });
  }); 	
};

NBC_Content.prototype.validate = function(){
   var contentForm = document.getElementById(''+NBC_Content.prototype.config.uploadFormName);
   if( validate_field(contentForm.user_email) &&
       validate_field(contentForm.name) &&
       validate_field(contentForm.user_name) &&       
       validate_field(contentForm.description) &&
       contentForm.terms.checked == true ){
       NBC_Content.prototype.isValid = true;
   } else {
       NBC_Content.prototype.isValid = false;
   }
};

function validate_field(field) {
    var result = false;
    if( field == null || field == "" ) {
        result = false;
    } else {
        result = true;
    }
    return result;
}

NBC_Content.prototype.showPreview = function() {
  $('#momentPreview').fadeIn("fast");
  nbc.submissionType = "moment";
  G.doPixelTracking(35);
  var $lefty = $("#momentPreview");
  $lefty.animate( {
    left : -286
  });
  $("#dropDownList").hide();
  $("#momentPreviewButton").addClass('momentPreviewOn');
  $("#momentPostButton").addClass('momentPostOn');
};

NBC_Content.prototype.displaySuccess = function() {
  window.location="/ugc/?message=success";   
};

NBC_Content.prototype.postContent = function() {
  var self = this;
    var momentTxt = $("#description").val();
    var token = $("#token").html(); 
    var payload = $("#payload").val();
    var placeholders = 'ugcStart[ sentFromStart[<sentFrom>]sentFromEnd sentFromNameStart[<sentFromName>]sentFromNameEnd ]ugcEnd';
    placeholders += ' CUSTOM_CODE_END]';
    payload = payload.replace('CUSTOM_CODE_END',placeholders);
    var momentTxtWPhoto = momentTxt + payload;
    var contentForm = document.getElementById(''+self.config.uploadFormName);
    var sentFrom = contentForm.user_email.value;
    var sentFromName = contentForm.user_name.value;
    var userPhone = contentForm.user_phone.value;
    var sentToEmail = contentForm.sent_to.value;
    momentTxtWPhoto = momentTxtWPhoto.replace("<sentFrom>",sentFrom);
    momentTxtWPhoto = momentTxtWPhoto.replace("<sentFromName>",sentFromName);
    var queryString = "action=add&ugccategory=New York/ugc&description=" + 
    escape(momentTxtWPhoto) + "&token=" + token +  "&tags=via_website"+
    "&adminTags=phone_"+userPhone+",sentto_"+sentToEmail + "&pendingStatus="+contentForm.status.value;
    
    U.log('/i/dispatcher/?h=content'+queryString);
    jQuery.ajax({
      url: "/i/dispatcher/?h=content",
      data: queryString,
      type: 'POST',
      dataType: 'json',
      success: function(data) {
        if (typeof data.ka !== "undefined" && data.ka.status == 1) {
          //add onclick handler to post to facebook  

	      if (self.countClicks.countSubmit == "0") {
	  	     nbc.submissionType = "moment";
	  	     G.doPixelTracking(36);  
	  	     self.countClicks.countSubmit = "1";
	      }
        self.displaySuccess();
       } 
          
        self.autoFill($("#momentCollTxtBox_area"), "");        
        
        $("#momentProcessing").css("display", "none");
        $("#momentCollTxtBox_area").removeClass("inlineTextAreaOpen");
        $("#momentCollTxtBox_area").addClass("inlineTextAreaClosed");
        $("#addMomentForm").css("opacity", 1);
        $("#inlineImageUpload").fadeOut();
        $("#inlineMomentCancel").fadeOut();
        $("#inlineDropDown").fadeOut();
        $("#inlineDropDownArrow").addClass('dropDownArrow');
        $("#postMomentForm").fadeOut("fast");
      }
    });
};

NBC_Content.prototype.hidePreview = function() {
  var $lefty = $("#momentPreview");
  $lefty.animate( {
    left : 13
  });
  $("#momentPreview").fadeOut("fast");
  $("#dropDownList").hide();
  $("#momentPreviewButton").removeClass('momentPreviewOn');
};

NBC_Content.prototype.addCancel = function() {
  var self = this;
  document.getElementById('postMomentForm').reset();
  self.momentSlideToggle();
  self.hidePreview();
  NBC_MomentUtil.removePhoto();
  $("#dropDownList").removeClass("momentADDPosition");
  $("#dropDownList").addClass("momentDDPosition");
  document.getElementById("momentPreviewTitle").innerHTML = "";
  document.getElementById("momentPreviewBody").innerHTML = "";
  $("#momentPreviewButton").removeClass('momentPreviewOn');
  $("#momentPostButton").removeClass('momentPostOn');
  $("#momentPreviewUserName").text(user.userName);
  $('#photoUploadLayer').fadeOut();
  $('#momentImageUploadBtn').hide();
};

NBC_Content.prototype.autoFill = function(id, v) {
  $(id).css( {
    color : "#797979"
  }).attr( {
    value : v
  }).focus( function() {
    if ($(this).val() === v) {
      $(this).val("").css( {
        color : "#797979"
      });
    }
  }).blur( function() {
    if ($(this).val() === "") {
      $(this).css( {
        color : "#797979"
      }).val(v);
    }
  });
};

NBC_Content.prototype.onMomentFocus = function() {
  U.log("moment: Subscribing to [overlay.closed] event.");
  NBC_EventManager.subscribe('overlay.closed', this, 'onOverlayClose');
  if (NBC_UserOverlay.validateLogin() && !this.moduleExpanded) {
    this.growTextEntryArea();
  }
};

NBC_Content.prototype.onOverlayClose = function() {
  U.log("moment: Handling [overlay.closed]");
  NBC_EventManager.unsubscribe('overlay.closed', this);
  if (user.isLoggedIn()) {
    this.growTextEntryArea();
  }
};
