
var isOpenSocial = true;

/** @const */
var GADGET_LINK = 'http://smart-gadget.appspot.com/myspace/all_for_good/all_for_good_raw_opensocial_v1.xml';

/**
 * Pour the data in template string.
 * @param {Object} datObject The data object to be filled in template string.
 * @return {string} The new string created from template string and filled
 *     with the given data.
 */
String.prototype.supplant = function(datObject) {
  return this.replace(/{([^{}]*)}/g,
    function(match, firstSubMatch) {
      var replace = datObject[firstSubMatch];
      return (typeof replace === 'string' || typeof replace === 'number') ?
          replace : match;
    }
  );
};

/**
 * Gives the x and y co-ordinates of mouse.
 * @param {object} element The element.
 * @return {object} The position of element.
 */
function getPosition(element) {
  var left = 0;
  var top = 0;
  while (element.offsetParent) {
    left += element.offsetLeft;
    top += element.offsetTop;
    element = element.offsetParent;
  }
  left += element.offsetLeft;
  top += element.offsetTop;
  return {x:left, y:top};
}

/**
 * This method will create HTML element string for single feed item.
 * @param {number} feedIndex Json feed with neccessary changes
 *     for single feed item.
 * @param {string} shareType The share type.
 *     It could be 'PROFILE', 'BLOG' (self values) or
 *     'email', 'notification', 'privateMessage', 'publicMessage', 'SHARE_APP' - recipient required.
 * @param {boolean} opt_isFriends If true, the message will be delivered
 *     to all viewer friends, otherwise to viewer.
 */
function shareContent(feedIndex, shareType, opt_isFriends) {
  if (!hasPermission()) {
    return;
  }
  shareType = shareType || 'PROFILE';
  var obj = feedRecords[feedIndex];
  var tplHtml = (shareType == 'PROFILE') ?
        _gel('tpl-share-content-profile').value :
        _gel('tpl-share-content-profile-blog-bulletin').value;
  var tplData = {
    title: obj.title,
    titleLink: obj.titleLink,
    location: obj.location,
    duration: obj.period,
    content: obj.desc
  };
  tplHtml = tplHtml.supplant(tplData);
  trace(tplHtml);
  trace('Length >>: ' + tplHtml.length);


  var recipients = opt_isFriends ? 'VIEWER_FRIENDS' : 'VIEWER';
  var recipientPerson = null;
  recipientPerson = window.friendPicker.selectedFriend;

  if(recipientPerson){
    recipients = recipientPerson.getId(); // Heere 'VIEWER_FRIENDS' will be overridden by the user-id of the recipient.
  }
  if (opt_isFriends) {
    if (!recipientPerson) {
      // please select a recipient!
      showFriendPicker();
      return;
    }
  }
  var params = {title: obj.title, type: shareType};
  var message = opensocial.newMessage(tplHtml, params);
  var reqSendMessageCallBack = function(response) {
    trace(response);
    trace(' response Had Error : '  + response.hadError());
    trace(' response data : '  + response.getData());
    trace(gadgets.json.stringify(response));
    if (!response.hadError()) {
    // TODO
    // successfully shared information could be stored in DB.
      if (shareType == 'notification') {
        //addToFavorite(feedIndex, 'bulletin');
      }
    }
  };
  opensocial.requestSendMessage(recipients, message, reqSendMessageCallBack);


}

/**
 * Toggles like state of an event.
 * @param {}
 *
 */
function toggleLike(feedIndex, state) {
  trace('toggleLike starts...');
  if (!hasPermission()) {
    return;
  }
  var obj = feedRecords[feedIndex];
  var newData = gData.ownerLike; // TODO clone implementataion.
  if (state) {
    newData[obj.itemId] = {
      itemId: obj.itemId,
      title: obj.title,
      titleLink: obj.titleLink,
      location: obj.location,
      enddate: obj.enddate,
      stdate: obj.stdate
    };
  } else {
    if(newData[obj.itemId]) {
      delete newData[obj.itemId];
    }
  }
  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'like', newData), 'updation');
  var callback = function(response) {
    var updateRequest = response.get('updation');
    trace('toggleLike hadError' + updateRequest.hadError());
    trace('toggleLike Error:' + updateRequest.getErrorMessage());
    trace('toggleLike data:' + updateRequest.getData());
    if(!updateRequest.hadError()) {
      trace('Successfully saved....');
    }
  };
  req.send(callback);
  trace('toggleLike ends...');
}




function loadFriendPicker() {trace('loadFriendPicker');
  window.friendPicker = new MyOpenSpace.Widgets.FriendPicker(
  {
    element: 'friend-picker',
    friendClickAction: pickedOneFriend,
    buildSelectedUI: false
  });
  trace('loadFriendPicker window.friendPicker' +  window.friendPicker);
}

function showFriendPicker(feedIndex, shareType, srcElement) {
  trace('showFriendPicker');
  if (!hasPermission()) {
    return;
  }
  if ((shareType != 'privateMessage') && (shareType != 'publicMessage')) {
    throw 'Unsupported share type';
  }
  window.currentShare = {
    feedIndex: feedIndex,
    shareType: shareType
  };
  var friendPickerElement = _gel('friend-picker');
  var elementPosition = getPosition(srcElement);
  friendPickerElement.style.left = elementPosition.x + 'px';
  var elementTop = elementPosition.y + 20;
  friendPickerElement.style.top = elementTop + 'px';
  trace('window.friendPicker' + window.friendPicker);
  if (window.friendPicker) {
    window.friendPicker.togglePopup();
    var friendPickerPopupStyle = window.friendPicker.popupWindow.style;
    var pickerBottom = elementTop +
        parseInt(friendPickerPopupStyle.borderTopWidth) +
        parseInt(friendPicker.displayHeight) +
        parseInt(friendPickerPopupStyle.borderBottomWidth);
    adjustIFrameHeight(pickerBottom);
  } else {
    // alert will not work in MySpace, since it is deprecated in Myspace.
    // trace can be replaced by information window.
    trace('Please wait till friend picker to load.');
  }
}

function pickedOneFriend(person) {
  var feedIndex = window.currentShare.feedIndex;
  var shareType = window.currentShare.shareType;
  shareContent(feedIndex, shareType, true);
  adjustIFrameHeight();
}


