
//MSGV.flashShareUrl='http://msgvarsity.com'; //default value
MSGV.flashShareUrl= "http://" + window.location.host;

function getShareURL(contentId) {
    var url = "";
    jq14.ajax({
        url: '/optimum/RetrievePremiumURL?id='+contentId,
        dataType: 'html',
        type: "post",
        async : false,
        success: function(data, textStatus, req){
          statusData = data;
          url = data;
        },
        error: function(req, status, error) {
            throw new Error("This browser does not support XMLHttpRequest.");
        }
      });
    return url;
}


//for flash videoplayer
//("Share:email", 1.232, "initiate", "clicked");
//Should probably be moved to the omniture.vm file
function videoOmnitureTracking(shareType, contentId, eventType, eventDetail, videoTitle) {
  
  if(eventType == "Open" || eventType == "Close"){

    s.eVar13=contentId;
    
    if(eventType == "Open"){
      s.events="event10";
    }else if(eventType == "Close"){
      s.events="event11";
    }
    
    if(MSGV.omniture.makeCall){
      MSGV.omniture.makeCall();
    }
 
  }else{
    if(MSGV.omniture.logSharingLink){
      MSGV.omniture.logSharingLink(shareType, "Video", contentId, eventType, eventDetail, videoTitle);
    }
  }
};

//for flash videoplayer  
function initPopup(type) {
  initPopupLoader(type,  MSGV.flashShareUrl,  MSGV.flashContentTitle, "Video", MSGV.flashContentTitle);
};

function initPopupLoader( type, toShareURL, contentId, contentType, contentTitle ) {
        var w = screen.width || 1024,
            h = screen.height || 768,
            fbPopupDimensions = [ 622, 422 ],
            
            fbURL = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(toShareURL),
            twitterPopupDimensions = [ 800, 600 ],
            twitterMessage = "Currently%20reading%20" + encodeURIComponent(toShareURL),
            twitterURL = "http://twitter.com/home?status=" + twitterMessage,
            URL,
            dimensions;
        switch( type )
        {
            case "fb":
                URL = fbURL;
                dimensions = fbPopupDimensions;
                break;
            case "twitter":
                URL = twitterURL;
                dimensions = twitterPopupDimensions;
                break;
            default:
                alert("Error: Undefined " + type );
        }

        var leftPos = ( w-dimensions[0] )*.5, topPos = ( h-dimensions[1] )*.5;

        day = new Date();
        id = day.getTime();
        var params = 'toolbar=1, scrollbars=1, location=1, statusbar=1, menubar=1, resizable=1, width='+ dimensions[0] +', height='+ dimensions[1] +', left = '+ leftPos +', top = '+ topPos;
        window.open( URL, id, params );
        
        //get contentid for articles (it should have been passed in for videos
        if(contentId == null && MSGV.likeAddFavObj){
          contentId = MSGV.likeAddFavObj.getContentId();
        }
        
      //get contentType for articles (it should have been passed in for videos
        if(contentType == null && MSGV.likeAddFavObj){
          contentType = MSGV.likeAddFavObj.getContentType();
        }
        
        if(contentTitle == null && MSGV.likeAddFavObj){
          contentTitle = MSGV.likeAddFavObj.getContentTitle();
        }
        
        if(MSGV.omniture.logSharingLink){
          MSGV.omniture.logSharingLink("Share:" + type, contentType, contentId, "completed", "clicked", contentTitle);
        }
    }
  
  
  (function(){
//    setting this instead in footer_incl_js.vm
//    if(polopoly.cookie.get('userId') != null){
//        jq14(".userId").val(polopoly.cookie.get('userId'));
//    }
    
    jq14('.facebook').click(function(){
        var url = getShareURL(getContentId());
        if (MSGV.isPhotosLike) {
           var photo = MSGV.Phts.get_current_image();
           var contentId = null;
           if(photo != null){
               contentId = photo.contentId;
               url = url + '#' + contentId;   
           }
        }
        
        initPopupLoader('fb', url);
        return false;
    })
    
    
    jq14('.twitter').click(function(){
        var url = getShareURL(getContentId());
        if (MSGV.isPhotosLike) {
           var photo = MSGV.Phts.get_current_image();
           var contentId = null;
           if(photo != null){
               contentId = photo.contentId;
               url = url + '#' + contentId;   
           }
        }
        
        initPopupLoader('twitter', url);
        return false;
    })
 
  // =============
  // = LoginPoup =
  // =============


//  var LoginPopController = function(settings){
//    var self = {};
//    var view = settings.view;
//    var styledPopup = MSGV.StyledPopup({popup: view, locationTarget: settings.launchButton});
//
//    self.show = styledPopup.show;
//    self.hide = styledPopup.hide;
//
//    view.find(".ok").click(function(){
//        MSGV.LikeAddFav.doLogin();
//  })
    
//    return self;
//  }

  // ===================
  // = ShareController =
  // ===================

  var ShareController = function(settings){
    var self = {};
    var data;
    var view = settings.view;
    var styledPopup;


    var init = function(){

      styledPopup = MSGV.StyledPopup({popup: settings.view, popupPosition: settings.pos, pos: settings.pos, locationTarget: settings.targetDiv});
   
      view.find(".send").click(function(){
        data = {
         "recipientName": view.find("input[name=rName]").val(),
         "recipientEmail": view.find("input[name=rEmail]").val(),
         "senderName": view.find("input[name=yourName]").val()
        }
        if(validate()){  
          data = jq14.extend(data, {
             "contentId": settings.contentId,
             "homeId": null,
             "userId": settings.userId,
             "childContentId": settings.childContentId
          })
          var shareUrl = settings.shareUrl + '?user-id=' + data.userId +
              '&content-id=' + data.contentId + '&recipient-name=' +
              data.recipientName + '&recipient-email=' + data.recipientEmail +
              '&sender-name=' + data.senderName;
          if (data.childContentId) {
              shareUrl = shareUrl + '&child-content-id=' + data.childContentId;
          }
          view.find(".loading").show();
          
          //interaction
          if(MSGV.omniture.logSharingLink){
            MSGV.omniture.logSharingLink("Share:email", settings.contentType, settings.contentId, "interact", "submit", settings.contentTitle);
          }
          jq14.post(
            shareUrl, 
            data,
            function(){
              self.showConfirmation(data);
              if(MSGV.omniture.logSharingLink){
                MSGV.omniture.logSharingLink("Share:email", settings.contentType, settings.contentId, "completed", "confirmation", settings.contentTitle);
              }
            })
        }
      })
    }

    var validate = function(){
      var invalidMessage = "Please enter a valid value for the following fields: <em>";
      var inValidFields = [];
      jq14.each(data, function(key, val){
        if(!val){
          inValidFields.push(key);
        }
      });
    
      if(inValidFields.length > 0){
        var fieldNamesMap = {
          "recipientName": "Recipient Name",
          "recipientEmail": "Recipient Email",
          "senderName": "Your Name"
        }
        jq14.each(inValidFields, function(index, fieldKey){
          invalidMessage += fieldNamesMap[fieldKey];
          if(index == inValidFields.length -1){
            invalidMessage += "</em>.";
          }else{
            invalidMessage += ", ";
          }
        })
        view.find(".errorMessages").html(invalidMessage).show();
        styledPopup.refresh();
        return false;
      }else{
        return true;
      }
    }

    self.showConfirmation = function(data){
      view.find(".errorMessages").hide();
      view.find(".fields").hide();
      view.find(".confirmation").show();
      view.find(".recipientName").text(data["recipientName"]);
      view.find(".done").click(self.hide);
      styledPopup.refresh();
    }

    self.show = function(){
      view.find(".fields").show();
      view.find(".confirmation").hide();
      styledPopup.show();
    }

    self.hide = function(){
      styledPopup.hide()
    }

    init();

    return self;
  }

  /*
    Container for popups styled with the liquid canvas plugin. Use this to show, hide, and do initial
    positioning of these elements.
  */

  
  MSGV = MSGV || {};  
  
  

  MSGV.LikeAddFav = function(settings){
    var self = {};
    var view = settings.view;
    var getChildContentId = settings.getChildContentId;
    var isLoggedIn = settings.isLoggedIn;
    var shareBar = view.find(".share_bar");
    var shareButton = view.find(".share");
    var shareTarget = view.find(".share");
    var likeButton = view.find(".like");
    var favoriteButton = view.find(".favorite");
    var emailButton = view.find(".email");
    var shareController;
    var loginPopController;
    var defaultSettings = {
      likeUrl:"/services/like",
      favoriteUrl: "/services/favorite",
      shareUrl: "/services/sharing",
      statusUrl: "/services/content-info",
      loginUrl: "/services/login",
      contentId: view.find('.fields [name=contentId]').val(),
      contentTitle: view.find('.fields [name=contentTitle]').val(),
      contentType: view.find('.fields [name=contentType]').val(),
      userId: view.find('.userId').val()
    };
//    var contentId = view.find('.contentId').val();

    settings = jq14.extend(defaultSettings, settings);
  
    // ============================
    // = General LikeAddFav Stuff =
    // ============================

    var statusData;
    var statusDataVal =  function(name){return jq14(statusData).find(name).text()};
  
    // update the status of the buttons
    var updateStatus = function(){
      
      var childContent = getChildContentId();
      var parentContentId = null;
      var contentId = null;
      if(childContent != null){
        contentId = childContent.contentId;
        parentContentId = settings.contentId;
      }else{
        contentId = settings.contentId;
      }
      
      
      var statusUrl = settings.statusUrl + '?user-id=' + settings.userId + '&content-id=' + contentId;
      if(parentContentId != null){
        statusUrl += "&parent-content-id=" + parentContentId;
      }
      
      jq14.ajax({
        url: statusUrl,
        dataType: 'xml',
        type: "post",
        success: function(data, textStatus, req){
          statusData = data;
          if( statusDataVal('like_status') == "true" ){
            likeButton.addClass("on");
          }else{
            likeButton.removeClass("on");
          }
          likeButton.find(".numLikes").text("(" + statusDataVal("likes") + ")");
          if(statusDataVal("favorite_status") == "true"){
            favoriteButton.addClass("favoriteOn");
          } else {
            favoriteButton.removeClass("favoriteOn");
          }
        },
        error: function(req, status, error) {
            //alert('Could not get like status.');
        }
      });
    }
  
    var doFavorite = function(){
      var childContent = getChildContentId();

      var parentContentId = null;
      var contentId = null;
      var contentType = null;
      var contentTitle = null;
      if(childContent != null){
        contentId = childContent.contentId;
        contentType = childContent.contentType;
        contentTitle = childContent.contentTitle;
        parentContentId = settings.contentId;
        
      }else{
        contentId = settings.contentId;
        contentType = settings.contentType;
        contentTitle = settings.contentTitle;
      }
      
      var url = settings.favoriteUrl + "?content-id=" + contentId;
      if(parentContentId != null){
        url += "&parent-content-id=" + parentContentId;
      }
      if(settings.homeId){
        url += "&home-id=" + settings.homeId;
      }
      if(settings.userId){
        url += "&user-id=" + settings.userId;
      }
      
      url += "&favorite=" + ((statusDataVal("favorite_status") == "true")? "false":"true");

      jq14.get(url, function(){
          updateStatus()
        //fire omniture request that the engagement has completed
        if(MSGV.omniture.logSharingLink){
          MSGV.omniture.logSharingLink("Favorite", contentType,  contentId, "completed", "clicked", contentTitle);
        }
      });
      
      //fire omniture request that the engagement has started(after the get call to not slow down the UI)
      if(MSGV.omniture.logSharingLink){
        MSGV.omniture.logSharingLink("Favorite", contentType, contentId, "initiate", "clicked", contentTitle);
      }
      
    }
    
    var doLike = function(){
      
      var childContent = getChildContentId();

      var parentContentId = null;
      var contentId = null;
      var contentType = null;
      var contentTitle = null;
      if(childContent != null){
        contentId = childContent.contentId;
        contentType = childContent.contentType;
        contentTitle = childContent.contentTitle;
        
        parentContentId = settings.contentId;
      }else{
        contentId = settings.contentId;
        contentType = settings.contentType;
        contentTitle = settings.contentTitle;
      }
      
      var url = settings.likeUrl + "?content-id=" + contentId;
      if(parentContentId != null){
        url += "&parent-content-id=" + parentContentId;
      }
      if(settings.homeId){
        url += "&home-id=" + settings.homeId;
      }
      if(settings.userId){
        url += "&user-id=" + settings.userId;
      }
      url += "&like=" + ((statusDataVal("like_status") == "true")? "false":"true");
      jq14.get(url, function(){
          updateStatus()
          //fire omniture request that the engagement has completed
        if(MSGV.omniture.logSharingLink){
          MSGV.omniture.logSharingLink("Like", contentType, contentId, "completed", "clicked", contentTitle);
        }
      })
      
      //fire omniture request that the engagement has started  (after the get call to not slow down the UI)
      if(MSGV.omniture.logSharingLink){
        MSGV.omniture.logSharingLink("Like", contentType, contentId, "initiate", "clicked", contentTitle);
      }
    }
  
//    var doLogin = function() {
//        var username = view.find('.username').val()
//        var password = view.find('.password').val()
//        var url = settings.loginUrl + "?username=" + username + "&password=" + password;
//        jq14.ajax({
//            type: "post",
//            url: url,
//            success: function(data){
//              styledPopup.hide()
//            }
//        });
//    }
    
    

    shareButton.toggle(
        function() {
            shareBar.show();
            shareButton.addClass('active').css({
                'color': '#FFFFFF'
            }).hover(
                function() {
                    shareButton.css({
                        'color': '#FFFFFF'
                    });
                },
                function() {
                    shareButton.css({
                        'color': '#FFFFFF'
                    });
                }
            );
            
            if(MSGV.omniture.logSharingLink){
              MSGV.omniture.logSharingLink("Share", settings.contentType, settings.contentId, "initiate", "clicked", settings.contentTitle);
            }
        },
        function() {
            shareBar.hide();
            shareButton.removeClass('active').css({
                'color': '#898989'
            }).hover(
                function() {
                    shareButton.css({
                        'color': '#FFFFFF'
                    });
                },
                function() {
                    shareButton.css({
                        'color': '#898989'
                    });
                }
            )
        }
    )
//    jq14('.sharing').hover(
//        function() {
//            shareBar.show()
//        }
//    )
    var doActionOrPromptLogin = function(action){
      if(polopoly.user.isLoggedIn()){
        action()
      }else{
        signIn();
      }
    }

    likeButton.click(function(){
      
        doActionOrPromptLogin(doLike);
    })

    favoriteButton.click(function(){
      doActionOrPromptLogin(doFavorite);
    })

    emailButton.click(function(){
      if(MSGV.omniture.logSharingLink){
        MSGV.omniture.logSharingLink("Share:email", settings.contentType, settings.contentId, "interact", "clicked", settings.contentTitle);
      }
      var childContentId = MSGV.isPhotosLike ? MSGV.Phts.get_current_image().contentId : null;
      shareController = ShareController(jq14.extend(settings,{
            view: view.find(".sharePop"),
            pos: {
               left: 200,
               top: 0
               },
            targetDiv: shareTarget,
            launchButton: emailButton,
            childContentId: childContentId
          }));
      
      doActionOrPromptLogin(shareController.show);
    })
    
    
    self.getContentId = function(){
      return settings.contentId;
    }
    
    self.getContentType = function(){
      return settings.contentType;
    }
    
    self.getContentTitle = function(){
      return settings.contentTitle;
    }
    
    
    //expose updateStatus()
    self.updateLikeFavStatus = function(){
      updateStatus();
    };

    self.draw = function(){
          if(polopoly.user.isLoggedIn()){
            updateStatus();
          }
    }

    self.draw();

    return self;
  }

  
  
})()

