/* ################################################################# */
/*                                                                   */
/*  TITLE:        NBC_MOMENT.JS                                      */
/*  LAST UPDATED: 10/13/2009                                          */
/*  UPDATED BY:   Viktoriya Eremeeva                         */
/*  RELEASE:      2009-10-29 - vicky                                         */
/*                                                                   */
/*  NAMESPACE: NBC_Moment                                            */
/*    mmt (instance of this class)                                   */
/*     @release 2009-10-15 - vicky                                                              */
/*  PREREQUISTES/DEPENDENCY:                                         */
/*    user                                                           */
/*    nbc                                                            */
/*    U.log                                                          */
/*    NBC_EventManager                                               */
/*                                                                   */
/* ################################################################# */
var NBC_Moment = function() {};

NBC_Moment.prototype.currCatIdx = 0;
NBC_Moment.prototype.currMomIdx = 0;
NBC_Moment.prototype.currMom;
NBC_Moment.prototype.momArr;
NBC_Moment.prototype.hasMoments;

NBC_Moment.prototype.nullMoment = {
  id: '', detail: '', rating: '', author: '', category: '', date: '', 
  commentCount: ''
};

NBC_Moment.prototype.countClicks = {
	countCancel: '',
	countSubmit: ''
};

NBC_Moment.prototype.cc;
NBC_Moment.prototype.init = function(momArr, argsArr) {
  NBC_EventManager.subscribe('user.login', this, 'updateMomentUser');
  NBC_EventManager.subscribe('user.logout', this, 'updateMomentUser'); 
  var self = this;

  if (typeof momArr != 'undefined') {
    self.momArr = momArr;
    self.currMom = self.retrieveMoment();
  } else {
    self.momArr = [];
  }
  self.hasMoments = self.momentsExist();
  
  var args = argsArr || [];

  $(document).ready( function() {
    // if no moments, eneter entry state
    if (!self.hasMoments) {
      U.log("No moments in the array. Entering entry state.");
      self.momentEntryState({disableFocus:true});
    }
    
    /* FOR EDITORS, SHOW EDIT LINK */
    if (user.isEditor()) {
      $("#momentAdmin").show();
    }

    /* AUTO PLAY */
    if (args.autoPlay && self.hasMoments) {
      self.autoPlay();
    }

    /* USER CLICKING INSIDE TEXTAREA */
    $("#momentCollTxtBox_area").click( function() {
      nbc.omniture = {
          firedRegistration : "Moment"
      };
      self.onMomentFocus();
    });

    // get together inline for agg page

    $("#momentCollTxtBox_area").click( function() {
    	if ($("#inlineImageUpload").is(":hidden")) {
    	  $(this).addClass("inlineTextAreaOpen").slideDown();
    	  $(this).removeClass("inlineTextAreaClosed");
    	  $("#inlineImageUpload").fadeIn();
    	  $("#inlineMomentCancel").fadeIn();
    	  $("#inlineDropDown").fadeIn();
    	}
    });
    
    $("#inlineMomentCancel").click( function() {
    	// U.log(self.countClicks.countCancel);
    	if (self.countClicks.countCancel == "0") {
	    	nbc.submissionType = "moment";
	        G.doPixelTracking(37);  
	        self.countClicks.countCancel = "1";
        }
        NBC_MomentUtil.removePhoto();
        $("#momentCollTxtBox_area").removeClass("inlineTextAreaOpen");
        $("#momentCollTxtBox_area").addClass("inlineTextAreaClosed");
        $("#inlineImageUpload").fadeOut();
        $("#inlineMomentCancel").fadeOut();
        $("#inlineDropDown").fadeOut();
        $("#inlineDropDownArrow").addClass("dropDownArrow");
     });
        
    $("#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(false);
    });
    $("#mom_nav_next").click( function() {
      self.displayNextMoment(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";

      self.momentEntryState();
      NBC_EventManager.fire("moment.entry.start"); 
    });

    /* ADMIN CONTROL */
    $("#editMomentLink").click( function() {
      self.edit();
    });
  });

  /* 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";
  });
  
  /* PLAY CONTROLS */
  $(document).ready( function() {
    // on user clicking Pause button
    $("#mmControl").click( function(event) {
      if (self.autoPlayOn) {
        self.stopAutoPlay();
      } else {
        self.autoPlay();
      }
    });
  });

  /** EXPANDED MODE */
  $(document).ready(function() {
    /* USER CLICKING CANCEL LINK */
    $("#momentCancelButton").click( function(event) {
    	// U.log(self.countClicks.countCancel);
    	if (self.countClicks.countCancel == "0") {
	    	nbc.submissionType = "moment";
	        G.doPixelTracking(37);  
	        self.countClicks.countCancel = "1";
        }	
  
      self.addCancel(); 
      self.autoPlay();
    });

    /* USER CLICKING PREVIEW */
    $("#momentPreviewButton").click( function(event) {
      self.showPreview(); 
    });

    /* USER CLICKING HIS NAME */
    $("#userId_button").click( function() {
      self.onUserSelect();
      self.momentFromStepOne();
    });

    /* PUBLISH TO FACEBOOK */
    $("#momentPublishFacebook").click(function() {
    	var mediaId = $("#fb_mediaId").val();
        var messTxt = $("#fb_messTxt").val();
        self.postToFacebook(mediaId, messTxt);
    });
    
    $("#momentPostButton").click( function() {
      if (!NBC_UserOverlay.validateLogin()) {
        return false;
      }
      self.postMoment();

      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_Moment.prototype.momentEntryState = function(options) {
  var self = this;
  self.momentSlideToggle();
  self.stopAutoPlay();
  $(".momentFormDiv").css("display", "");
  if (typeof options !== "undefined" && options.disableFocus) {
    // don't do anything (no focus)
  }
  else {
    $("#momentCollTxtBox_area").focus();  
  }
};

//AUTO PLAY
NBC_Moment.prototype.autoPlayOn = false;
NBC_Moment.prototype.autoForwardTimeout = 7500; /* 7.5 secs */
NBC_Moment.prototype.autoMaxInCat = 2; /* how many to display in each category */
NBC_Moment.prototype.autoForwardMoment = function() {
  var self = this;
  if (self.autoPlayOn) {
    setTimeout( function() {
      mmt.autoForwardMoment();
    }, self.autoForwardTimeout);
  } else {
    return;
  }

  var diff = (new Date().valueOf() - self.displayMomentExecutedOn);
  if (diff < (self.autoForwardTimeout - 1000)) {
    U.log("moment: Not forwarding to next moment. Diff from last execution is only: " + diff);
    return;
  }

  // if the next moment exceeds the max in category OR no more moments in the cat
  if (self.currMomIdx >= self.autoMaxInCat || 
      ((self.currMomIdx + 1) >= self.momArr[self.currCatIdx].length)) {
    // change the category
    self.currCatIdx = self.getNextCatIdx();
    self.currMomIdx = 0;
    self.changeCat(self.currCatIdx);
  } else {
    self.displayNextMoment(true, true);
  }
};

NBC_Moment.prototype.momentsExist = function() {
  if (this.momArr.length === 0) {
    return false;
  }
  for (var i = 0, len = this.momArr.length; i < len; i++) {
    if(this.momArr[i].length > 0) {
      return true;
    }
  }
  return false;
};

NBC_Moment.prototype.autoPlay = function() {
  var self = this;
  if (self.autoPlayOn) {
    U.log("moment: WARN: trying to start auto play again. Already started.");
    return;
  }
  if (!self.hasMoments) {
    U.log("Not starting auto play: no moments exist.");
    return;
  }
    
  U.log("moment: starting auto play");
  self.autoPlayOn = true;
  $("#mmControl").attr("class", "mmCtrlPause");
  setTimeout( function() {
    mmt.autoForwardMoment();
  }, self.autoForwardTimeout);
};

NBC_Moment.prototype.stopAutoPlay = function() {
  if (this.autoPlayOn) {
    U.log("moment: stopping auto play");
    this.autoPlayOn = false;
    $("#mmControl").attr("class", "mmCtrlPlay");
  }
};

NBC_Moment.prototype.retrieveMoment = function(catIdx, momIdx) {
  // retrieve current moment if no arguments specified
  if (arguments.length === 0) {
    catIdx = this.currCatIdx;
    momIdx = this.currMomIdx;
  }

  if (typeof this.momArr[catIdx] == 'undefined' || 
      typeof this.momArr[catIdx][momIdx] == 'undefined') {
    this.nullMoment.category = this.getCurrCatName();
    return this.nullMoment;
  }
  return this.momArr[catIdx][momIdx];
};

NBC_Moment.prototype.current = function() {
  return this.currMom;
};

NBC_Moment.prototype.getCatMomentCount = function() {
  if (typeof this.momArr[this.currCatIdx] === 'undefined') {
    return 0;
  }
  return this.momArr[this.currCatIdx].length;
};

NBC_Moment.prototype.getMomentIdx = function(goToNext) {
  if (typeof this.momArr[this.currCatIdx] === 'undefined') {
    return 0;
  }

  if (goToNext) {
    // array size should be more than current idx        
    if (this.momArr[this.currCatIdx].length > (this.currMomIdx + 1)) {
      this.currMomIdx++;
    } else {
      this.currMomIdx = 0;
    }
  } else {
    if (this.currMomIdx > 0) {
      this.currMomIdx--;
    } else {
      this.currMomIdx = this.momArr[this.currCatIdx].length - 1;
    }
  }
  return this.currMomIdx;
};

NBC_Moment.prototype.displayMomentExecutedOn = 0;
NBC_Moment.prototype.displayMoment = function(moment, fadeIn) {
  var self = this;

  var momDetail = moment.detail;
  var imgTag = "";
  if (typeof moment.photoBase !== "undefined" && moment.photoBase !== "") {
    imgTag = "<span class='momentImage' style=\"background-image:url('" + 
    moment.photoBase + "320X240.jpg')\"></span>";
    momDetail = imgTag + moment.detail;
  }

  // moment attributes
  $("#momentDate").text(moment.date);
  $("#momentCategoryIdx").text((self.currMomIdx + 1));
  $("#momentMaxCount").text(self.getCatMomentCount());
  $("#momentAuthor").text(moment.authorDisplayName);
  $("#momentAuthorLink").attr("href",
      "/user/profile/?uid=" + moment.authorUid);
  
  $("#momentCommentLink").attr("href",
	      "/somycity/?mediaId="+ moment.id);
  $("#momentRatingLink").attr("href",
	      "/somycity/?mediaId="+ moment.id);

  var momentShareRR1 = $("#momentShareRR"); 
  var momentShareRR2 = document.getElementById("momentShareRR"); 
  if(jQuery.browser.msie){
	
	  momentShareRR2.setAttribute('onclick', function() {
		  var stringtext = moment.id;
		  mmt.shareColl(moment.id, moment.authorUid, moment.author, moment.detail, this);
		  return false;
	  });
  }
  else {
	  momentShareRR1.attr('onclick', "javascript:mmt.shareColl(\""+moment.id + "\", \"" + moment.authorUid + "\", \"" + moment.author + "\", \"" + moment.detail + "\",  this)");
  }
  var $detail = $("#momentDetail"), $comments = $(".momentComments"), $rating = $("#momentRating");

  $detail.html(momDetail);
  $comments.html(moment.commentCount + 
      (moment.commentCount == 1 ? " comment" : " comments"));
  $rating.html(moment.rating + "%");

  var FADE_IN = 0;
  if (typeof fadeIn != "undefined" && fadeIn) {
    FADE_IN = 1500;
  }
  if (FADE_IN > 0) {
    $detail.hide().fadeIn(FADE_IN);
    $comments.hide().fadeIn(FADE_IN);
    $rating.hide().fadeIn(FADE_IN);
  }

  // update the execute time
  self.displayMomentExecutedOn = parseInt(new Date().valueOf(), 10);
};

NBC_Moment.prototype.displayNextMoment = function(goToNext, fadeIn) {
  this.currMomIdx = this.getMomentIdx(goToNext);
  this.currMom = this.retrieveMoment(this.currCatIdx, this.currMomIdx);
  this.displayMoment(this.currMom, fadeIn);
};

NBC_Moment.prototype.changeCat = function(catIdx) {
  var self = this;
  self.currCatIdx = catIdx;
  self.currMomIdx = 0;
  self.currMom = self.retrieveMoment();
  var currCatName = self.getCurrCatName();
  // U.log("moment: changing category to [" + currCatName + "] at index [" + catIdx + "]");
  self.displayMoment(self.currMom, true);
  $("#currCatName").text(currCatName).hide().fadeIn();
  $(".currCatName").text(currCatName);
  $("#currCatName2").text(currCatName);
  $("#currCatName3").text(currCatName);
  $("#catNav_wrp li a").removeClass("currentCategory");
  $("#cat" + self.currCatIdx).addClass("currentCategory");
  $("#currCatHref").attr("href", "/somycity/?categories=" + currCatName);

  $("#momentPreviewMain .momentPreviewCategory").text(currCatName);
};

NBC_Moment.prototype.getCurrCatName = function() {
  if (typeof momCatArr[this.currCatIdx] === "undefined") {
    U.log("WARNING: moment category at index [" + this.currCatIdx + "] does not exist!");
    return "";
  }
  return momCatArr[this.currCatIdx];
};

NBC_Moment.prototype.displayOnclickNextMoment = function(goToNext, fadeIn) {
  this.currMomIdx = this.getMomentIdx(goToNext);
  this.currMom = this.retrieveMoment(this.currCatIdx, this.currMomIdx);
  this.displayMoment(this.currMom, fadeIn);
};

/**
 * Retrieves the next category down the list. If the next category is empty,
 * returns the first index.
 */
NBC_Moment.prototype.getNextCatIdx = function() {
  if (typeof this.momArr[this.currCatIdx + 1] == 'undefined') {
    return 0;
  }

  if (this.momArr[this.currCatIdx + 1].length > 0) {
    return this.currCatIdx + 1;
  }

  // the next category has no items, try to find one that has it  
  var tempCatIdx = this.currCatIdx + 2;
  for ( var i = tempCatIdx; i < this.momArr.length; i++) {
    if (typeof this.momArr[i] != 'undefined' && this.momArr[i].length > 0) {
      return i;
    }
  }
  // could not find the next category with items, return to the first
  return 0;
};

NBC_Moment.prototype.getMomentId = function(momId) {
  if (U.isNotNull(momId)) {
    return momId;
  } else {
    // default to the current moment
    return this.retrieveMoment().id;
  }
};

//share this moment
NBC_Moment.prototype.share = function(momId, userId, userName, momentBodyText, momField) {
  U.log("share: share method called");
  var self = this;
  var id = self.getMomentId(momId);
  var shareString = encodeURIComponent(nbc.domain +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName="+userName)+"&title=NBC Moment";
  var shareStringNoTitle = encodeURIComponent(nbc.domain +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName="+userName);
  var getHref="";
  var getIndexOfLink="";
  var getNewUrl="";
  $("#moment_share_box .delico").find("a").each(function() {
	$(this).attr("href","http://del.icio.us/post?url="+ shareString);
  });
  $("#moment_share_box .buzz").find("a").each(function() {
	getHref = $(this).attr("href");
	getIndexOfLink = getHref.indexOf("guid=");
	getNewUrl = getHref.substring(0, getIndexOfLink+5)+escape(shareStringNoTitle) + "&targetUrl=";
	$(this).attr("href", getNewUrl);
  });
  $("#moment_share_box .myspace").find("a").each(function() {
    $(this).attr("href", "http://www.myspace.com/Modules/PostTo/Pages/?u="+shareStringNoTitle+"&t=NBC Moment");
  });
  $("#moment_share_box .digg").find("a").each(function() {   
	$(this).attr("href", "http://digg.com/submit?phase=2&url="+shareStringNoTitle +"&bodytext="+ escape(momentBodyText));
  });
  $("#moment_share_box .fark").find("a").each(function() {
	 getHref = $(this).attr("href");
	 getIndexOfLink = getHref.indexOf("u=");
	 getNewUrl = getHref.substring(0, getIndexOfLink+2)+escape(shareStringNoTitle);
	 $(this).attr("href", getNewUrl);
  });
  $("#moment_share_box .facebook").find("a").each(function() {
	  $(this).attr("href", "http://www.facebook.com/sharer.php?u=" + shareStringNoTitle);
  });	  
  $("#moment_share_box_coll").hide("fast");
  $("#moment_share_box_rr").hide("fast");
  $("#moment_share_box").hide("fast");
  $("#moment_share_box").show("fast");
};

//share this moment
NBC_Moment.prototype.shareRR = function(momId, userId, userName, momentBodyText, momField) {
  U.log("shareRR: share method called");
  var self = this;
  var id = self.getMomentId(momId);
  var shareString = encodeURIComponent(nbc.domain +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName="+userName)+"&title=NBC Moment";
  var shareStringNoTitle = encodeURIComponent(nbc.domain +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName="+userName);
  var getHref="";
  var getIndexOfLink="";
  var getNewUrl="";
  $("#moment_share_box_rr .delico").find("a").each(function() {
	$(this).attr("href","http://del.icio.us/post?url="+ shareString);
  });
  $("#moment_share_box_rr .buzz").find("a").each(function() {
	getHref = $(this).attr("href");
	getIndexOfLink = getHref.indexOf("guid=");
	getNewUrl = getHref.substring(0, getIndexOfLink+5)+escape(shareStringNoTitle) + "&targetUrl=";
	$(this).attr("href", getNewUrl);
  });
  $("#moment_share_box_rr .myspace").find("a").each(function() {
    $(this).attr("href", "http://www.myspace.com/Modules/PostTo/Pages/?u="+shareStringNoTitle+"&t=NBC Moment");
  });
  $("#moment_share_box_rr .digg").find("a").each(function() {   
	$(this).attr("href", "http://digg.com/submit?phase=2&url="+shareStringNoTitle +"&bodytext="+ escape(momentBodyText));
  });
  $("#moment_share_box_rr .fark").find("a").each(function() {
	 getHref = $(this).attr("href");
	 getIndexOfLink = getHref.indexOf("u=");
	 getNewUrl = getHref.substring(0, getIndexOfLink+2)+escape(shareStringNoTitle);
	 $(this).attr("href", getNewUrl);
  });
  $("#moment_share_box_rr .facebook").find("a").each(function() {
	  $(this).attr("href", "http://www.facebook.com/sharer.php?u=" + shareStringNoTitle);
  });	  
  $("#moment_share_box_coll").hide("fast");
  $("#moment_share_box").hide("fast");
 $("#moment_share_box_rr").hide("fast");
  $("#moment_share_box_rr").show("fast");
};

//share this moment on module
NBC_Moment.prototype.shareColl = function(momId, userId, userName, momentBodyText, momField) {
  var self = this;
  var id = self.getMomentId(momId);
  var shareString = encodeURIComponent(nbc.domain +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName="+userName)+"&title=NBC Moment";
  var shareStringNoTitle = encodeURIComponent(nbc.domain  +"/somycity/?mediaId=" + id+"&userId="+userId+"&userName=" +userName);
  var getHref="";
  var getIndexOfLink="";
  var getNewUrl="";
  $("#moment_share_box_coll .delicio").find("a").each(function() {
	$(this).attr("href","http://del.icio.us/post?url="+ shareString);
  });
  $("#moment_share_box_coll .buzz").find("a").each(function() {
	getHref = $(this).attr("href");
	getIndexOfLink = getHref.indexOf("guid=");
	getNewUrl = getHref.substring(0, getIndexOfLink+5)+escape(shareStringNoTitle) + "&targetUrl=";
	$(this).attr("href", getNewUrl);
  });
  $("#moment_share_box_coll .myspace").find("a").each(function() {
    $(this).attr("href", "http://www.myspace.com/Modules/PostTo/Pages/?u="+shareStringNoTitle+"&t=NBC Moment");
  });
  $("#moment_share_box_coll .digg").find("a").each(function() {   
	  U.log("momentBodyText "+momentBodyText);
	$(this).attr("href", "http://digg.com/submit?phase=2&url="+shareStringNoTitle+"&bodytext="+escape(momentBodyText));
  });
  $("#moment_share_box_coll .fark").find("a").each(function() {
	 getHref = $(this).attr("href");
	 getIndexOfLink = getHref.indexOf("u=");
	 getNewUrl = getHref.substring(0, getIndexOfLink+2)+escape(shareStringNoTitle);
	 $(this).attr("href", getNewUrl);
  });
  $("#moment_share_box_coll .facebook").find("a").each(function() {
	  $(this).attr("href", "http://www.facebook.com/sharer.php?u=" + shareStringNoTitle);
  });	  
  $("#moment_share_box_rr").hide("fast");
  $("#moment_share_box").hide("fast");
  $("#moment_share_box_coll").show("fast");
  NBC_EventManager.fire("moment.share.click");   
};

//show each layer
NBC_Moment.prototype.showMomentLayer = function(momentContentDiv) {
  $("#mainMomentBody .hot_top_sub").hide();
  document.getElementById(momentContentDiv).style.display = 'block';
  var showCategorySelected = document.getElementById('catNav')
  .getElementsByTagName('a');
};

NBC_Moment.prototype.countDown;
NBC_Moment.prototype.countDownFinished = function() {
  var self = this;
  $("#viewYourMomentWaitText").hide();
  $("#viewYourMomentButton").show();
};

NBC_Moment.prototype.postMoment = function() {
  var self = this;
  var isAnonymousPost = false; 
  var momentTxt = $("#momentCollTxtBox_area").val();
  if (momentTxt !== "") {
    $("#momentProcessing").css("display", "block");
    $("#addMomentForm").css("opacity", 0.3);
    $("#inlineMomentForm").css("opacity", 0.3);

    if ($("#anonymous_button").attr("checked")) {
      passedToken = nbc.user.anon.token;
      passedName = nbc.user.anon.name;
      passedUid = nbc.user.anon.id;
      U.log("moment: Anonymous user posting a moment");
      isAnonymousPost = true;
    } else {
      passedToken = user.token;
      passedName = user.userName;
      passedUid = user.userId;
      U.log("moment: Logged in user posting a moment");
    }

    var momentTxtWPhoto = momentTxt + $("#momentPhotoPayload").val();
    var queryString = "action=add&category=" + self.getCurrCatName() + 
        "&description=" + escape(momentTxtWPhoto) + "&token=" + passedToken + 
        "&tags=via_website";
    jQuery.ajax({
      url: "/i/dispatcher/?h=moment",
      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  
          $("#fb_mediaId").val(data.ka.mediaId);
          $("#fb_messTxt").val(momentTxt);
  
          // add href to view your moment
          $("#viewYourMomentButton, #momentPublish").show();
          $("#viewYourMomentWaitText").hide();
          U.log(self.countClicks.countSubmit);
	      if (self.countClicks.countSubmit == "0") {
	  	     nbc.submissionType = "moment";
	  	     U.log("isAnonymousPost "+isAnonymousPost);
	  	     if (isAnonymousPost == false) { G.doPixelTracking(36); }
	  	     else { G.doPixelTracking(32); } 
	  	     self.countClicks.countSubmit = "1";
	      }
          self.setupViewYourMomentButton(queryString,data.ka.mediaId,passedName, passedUid);    
        } 
        else { // error occured
          $("#viewYourMomentWaitText,#viewYourMomentButton, #momentPublish").hide();
  
          var error;
          if (typeof data.ka !== "undefined" && typeof data.ka.error !== "undefined") {
            error = data.ka.error;
          }
          else if (typeof data.error !== "undefined") {
            error = data.error;
          }
          U.log("moment: Error posting moment: " + error);
        }
  
        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");
        
        self.momentThankYou();
        self.addCancel();
      }
    });
  }
};

NBC_Moment.prototype.hidePreview = function() {
  var $lefty = $("#momentPreview");
  $lefty.animate( {
    left : 13
  });
  $("#momentPreview").fadeOut("fast");
  $("#dropDownList").hide();
  $("#momentPreviewButton").removeClass('momentPreviewOn');
};

NBC_Moment.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_Moment.prototype.momentSlideToggle = function() {
  $(".momentFormDiv").slideToggle();
  $("#dropDownList").hide();
};

NBC_Moment.prototype.preview = function(id1, id2, id3) {
  var titleCharCount = 25;
  var maxCharCount = 550;
  var NewText = document.getElementById(id1).value;

  splitText = NewText.split(/\n/).join("<br />");
  var DivElementTitle = document.getElementById(id2);
  if (DivElementTitle) {
    DivElementTitle.innerHTML = splitText.substring(0, titleCharCount);
  }
  var DivElementBody = document.getElementById(id3);  
  if (DivElementBody) {
    DivElementBody.innerHTML = splitText.substring(titleCharCount, maxCharCount);
  }
};

NBC_Moment.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_Moment.prototype.backToMain = function() {
  $('#momentThankYou').fadeOut();
  this.resetMomentEntry();
}; 

NBC_Moment.prototype.resetMomentEntry = function() {
  $("#momentCollTxtBox_area").addClass("inlineTextAreaOpen");
  $("#momentCollTxtBox_area").removeClass("inlineTextAreaClosed");
  $("#inlineImageUpload").fadeIn("fast");
  $("#inlineMomentCancel").fadeIn("fast");
  $("#inlineDropDown").fadeIn("fast");
  $("#inlineDropDownArrow").removeClass('dropDownArrow');
  $("#postMomentForm").fadeIn("fast");  
}; 


NBC_Moment.prototype.momentThankYou = function() {
  var self = this;
  self.hidePreview();
  $('#momentThankYou').fadeIn();
};

/** POST TO FACEBOOK FROM ADD MODULE PAGE **/
NBC_Moment.prototype.postToFacebook = function(mediaId, momentTxt) {	
  U.log("moment: posting to facebook");
  var templateData = {};
  var imagesArray={};
  var imagesArray2={};
  var imagesArray={};
  var imagesArray2={};
  var imgSrcMoment = nbc.mediaDomain+"/designimages/nbc_moment_so_"+nbc.siteKey+".gif";

  if (($("#momentPhotoPayloadPreview")) && ($("#momentPhotoPayloadPreview").attr("src")) && ($("#momentPhotoPayloadPreview").attr("src") != "")) {
  	var imgUpload = $("#momentPhotoPayloadPreview").attr("src");
    if (imgUpload.indexOf("grey_space.gif") != -1) {
    	imgSrcMoment = imgUpload;
    }
  }
  
  U.log("final imgSrcMoment "+imgSrcMoment);
  imagesArray2["src"] =  imgSrcMoment;
  imagesArray2["href"]=nbc.fullDomain+ "/somycity/?mediaId=" + mediaId+"&userName=" + user.userName + "&userId=" + user.userId;
  U.log(imagesArray2['src']+" "+imagesArray2['href']);
  imagesArray[0]= imagesArray2;
  templateData.images=imagesArray;
  templateData.moment_url = "http://"+ nbc.domain + "/somycity/?mediaId=" + mediaId+"&userName=" + user.userName + "&userId=" + user.userId+"&__source=Facebook";
  // alert(templateData.moment_url);
  templateData.site_url = "http://" + nbc.domain+"/somycity/";
  templateData.site_name = nbc.brand;
  templateData.moment = momentTxt;
  templateData.somycity_brand = nbc.soMyCityBrand;
  facebook_publish_feed_story(nbc.fb.momentBundleId, templateData);
};

//grow and shrink the box
NBC_Moment.prototype.moduleExpanded = false;
NBC_Moment.prototype.growTextEntryArea = function() {
  this.moduleExpanded = true;
  this.stopAutoPlay();

  // make sure username is there
  $("#userName").text(user.userName);
};

NBC_Moment.prototype.goToMomentAgg = function(momId) {
  var currMom = this.retrieveMoment(); // get current moment
  var goToMomId = momId || currMom.id;
  var currentMomentUrl = "/somycity/?mediaId=" + goToMomId + 
      "&userId=" + currMom.authorUid + "&userName=" + currMom.author;
  window.location.href = currentMomentUrl;
};

NBC_Moment.prototype.setupViewYourMomentButton = function(momentDetailQs, momId, userName, userId) {
  var currMom = this.retrieveMoment(); // get current moment  
  $("#viewYourMomentButton").click(function() {
    U.log("moment: setting view your moment detail to [" + momentDetailQs + "]");
    $('#viewYourMomentForm input[name="detail"]').val(momentDetailQs);
    var formAction = "/somycity/?mediaId=" + momId + "&userName=" + userName + "&userId=" + userId;
    U.log("moment: Changing form action to [" + formAction + "]");
    $form = $("#viewYourMomentForm");
    $form.attr("action", formAction);
    $form.submit();    
    return false; // prevent default action
  });
};

NBC_Moment.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_Moment.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_Moment.prototype.onOverlayClose = function() {
  U.log("moment: Handling [overlay.closed]");
  NBC_EventManager.unsubscribe('overlay.closed', this);
  if (user.isLoggedIn()) {
    this.growTextEntryArea();
  }
};

//on user login
NBC_Moment.prototype.updateMomentUser = function() {
  if (!user.isLoggedIn()) {
    // not logged in
    $("#momentAdmin").hide();
    U.log("Edit admin links are hidden.");
  } 

  else {
    // logged in
    // add name to preview
    $("#momentPreviewUserName").text(user.userName);
    if (user.isEditor()) {
      $("#momentAdmin").show();
      U.log("Edit admin links showing.");
    }
  }
};

NBC_Moment.prototype.goToUserProfile = function() {
  window.location.href = "/user/profile/?uid=" + this.current().authorUid;
};
 
/* set up position for share box */
function position(o) {
  var canvas = document.getElementById("canvas");
  var leftPos = U.getPosition(o).x - U.getPosition(canvas).x;
  $("#moment_share_box").css("top", U.getPosition(o).y).css("left", leftPos);
}

function positionRR(o) {
	var pos = Position.get(o);
	var canvas = document.getElementById("canvas");
	var leftPos = U.getPosition(o).x - U.getPosition(canvas).x;
	$("#moment_share_box_rr").css("top", U.getPosition(o).y).css("left", leftPos);
}

function positionColl(o) {
	var pos = Position.get(o);
	var canvas = document.getElementById("canvas");
	var leftPos = U.getPosition(o).x - U.getPosition(canvas).x;
	$("#moment_share_box_coll").css("top", U.getPosition(o).y).css("left", leftPos);
}

$(document).ready(function() {
    var dragShareHeader = $("#moment_share_box .share_header");
    $('#moment_share_box').jqDrag(dragShareHeader);
    dragShareHeader.mouseup(function() {
         $(this).css("opacity","1");
         $("#moment_share_box a.share_close").css("display","block");
         $("#moment_share_box a.share_close").css("opacity","1");
         $("#moment_share_box a.share_close").css("display","block");
    }); 
    var dragShareRRHeader = $("#moment_share_box_rr .share_header");
    $('#moment_share_box_rr').jqDrag(dragShareRRHeader);
    dragShareRRHeader.mouseup(function() {
         $(this).css("opacity","1");
         $("#moment_share_box_rr a.share_close").css("display","block");
         $("#moment_share_box_rr a.share_close").css("opacity","1");
         $("#moment_share_box_rr a.share_close").css("display","block");
    }); 
    var dragShareCollHeader = $("#moment_share_box_coll .share_header");
    $('#moment_share_box_coll').jqDrag(dragShareCollHeader);
    dragShareCollHeader.mouseup(function() {
         $(this).css("opacity","1");
         $("#moment_share_box_coll a.share_close").css("display","block");
         $("#moment_share_box_coll a.share_close").css("opacity","1");
         $("#moment_share_box_coll a.share_close").css("display","block");
    }); 
}); 
 
 
