// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


String.prototype.pluralize = function(count, plural) {
  if (plural == null)
    plural = this + 's';

  return count + " " + (count == 1 ? this : plural)
};

function friendSelectorOnClick(event) {
    chooseFriend(Event.findElement(event, 'LI'));
    this.hide();
};

// Tweaked from onClick in Autocompleter.Base
function chooseFriend(friendElem) {
    var fb_uid = friendElem.id.replace('facebook_uid', '');

	// only add friend if they haven't already been selected before
	if ($('selected' + fb_uid) == null) {
		$('new_hangout').insert("<input id='input" + fb_uid +"' type='hidden' class='friend-input' name='hangout_members[]' value=" + fb_uid + " />");
        //$('selectedFriends').down('.list').insert(picked);

        // for hangouts/new        
        //$('selectedFriends').down('.list').insert("<div style='float: left; margin-right: 10px; margin-bottom: 15px; border: 1px solid #EAEAEA; width:50px;height:50px' id=selected" + fb_uid + "><div class=\"selectedFriend hidden\">" + friendElem.down(5).innerHTML + "</div><div class=\"profile-pic\"><fb:profile-pic linked=\"false\" uid=\"" + fb_uid + "\" width=\"50\" height=\"50\" size=\"square\"></fb:profile-pic></div>  <div id=remove" + fb_uid + " style='display:none; margin-top:-40px; margin-left:10px; height:27px; width:27px; position:relative; background:url(\"/images/icon_remove_friends.png\")'></div>  </div>");
        //FB.XFBML.parse($('selected' + fb_uid));
        
        // for home feed
        $('selectedFriends').down('.list').insert("<div class='profile-thumb' id=selected" + fb_uid + "><div class=\"selectedFriend hidden\">" + friendElem.down(5).innerHTML + "</div><fb:profile-pic linked=\"false\" uid=\"" + fb_uid + "\" width=\"33\" height=\"33\" size=\"square\"></fb:profile-pic><div id=remove" + fb_uid + " style='display:none; cursor: pointer; margin-top: -35px; height:33px; width:33px; position:relative; background:url(\"/images/icon_remove_friends.png\") center center no-repeat'></div></div>");
        FB.XFBML.parse($('selected' + fb_uid));
        
        if($('placeHolderThumb')) $('placeHolderThumb').remove();
        updateHeader();
    
		// remove friend if you accidentally select him/her
		Event.observe('selected' + fb_uid, 'click', function(event) {
		    $('selected' + fb_uid).remove();
			$('input' + fb_uid).remove();
            updateHeader();
		});

        Event.observe('selected' + fb_uid, 'mouseover', function() {
            $('remove' + fb_uid).show();
        });
        
        Event.observe('selected' + fb_uid, 'mouseout', function() {
            $('remove' + fb_uid).hide();
        });

	}

	$('friendSelector').value = "";
	$('friendSelector').focus();
};

function updateHeader() {
    return;
    var headerString;
    if ($$(".selectedFriend").size() == 1)  headerString = "You ";
    else headerString = "You, ";
    if ($$(".selectedFriend").size() == 0) {
        headerString = "You and... are...";
        $('selectedFriends').down('.headerSentence').update(headerString);
        return;
    }
    
    $$(".selectedFriend").each(function(f, index){
        if (f != $$(".selectedFriend").last()) headerString = headerString + f.innerHTML.match(/[\w]+\b/) + ", ";
        else headerString = headerString + "and " + f.innerHTML.match(/[\w]+\s/) + " are...";
    });
    $('selectedFriends').down('.headerSentence').update(headerString);
};

function insertPlaceholder() {
        $('selectedFriends').down('.list').insert("<div style='background: url(\"/images/thumb_placeholder.png\"); float: left; margin-right: 10px; margin-bottom: 15px; border: 1px solid #EAEAEA; width:50px;height:50px' id=placeHolderThumb></div>");
}

// Tweaked from onShow in Autocompleter.Base
function friendSelectorOnShow(element, update) {
    if(!update.style.position || update.style.position=='absolute') {
      update.style.position = 'absolute';
      Position.clone(element, update, {
        setHeight: false,
        offsetTop: element.offsetHeight
      });
    }
    Effect.Appear(update,{duration:0.15});  
};

// Tweaked from the selector method in Autocompleter.Local
function friendSelectorFn(instance) {
    var ret       = []; // Beginning matches
    var partial   = []; // Inside matches
    var entry     = instance.getToken();
    var count     = 0;
    var makeElem = function (elem, partial) {
        var nameText = "";
        if (partial) {
            nameText = elem.name.substr(0, foundPos) + "<strong>" + elem.name.substr(foundPos, entry.length) + "</strong>" + elem.name.substr(foundPos + entry.length);
        } else {
            nameText = "<strong>" + elem.name.substr(0, entry.length)  + "</strong>" +  elem.name.substr(entry.length);
        }
        return "<li id=facebook_uid" + elem.facebook_uid + "><div class=\"profile-pic\"><fb:profile-pic linked=\"false\" uid=\"" + elem.facebook_uid + "\" width=\"35\" height=\"35\" size=\"square\"></fb:profile-pic></div><div class=\"name\">" + nameText + "</div><div class=\"hidden real-name\">" + elem.name + "</div><div class=\"clear\"></div></li>";
    };

    for (var i = 0; i < instance.options.array.length && ret.length < instance.options.choices ; i++) {
        var elem = instance.options.array[i];
        var foundPos = instance.options.ignoreCase ? elem.name.toLowerCase().indexOf(entry.toLowerCase()) : elem.name.indexOf(entry);
          
        while (foundPos != -1) {
          if (foundPos == 0 && elem.name.length != entry.length) {
            ret.push(makeElem(elem));
            break;
          } else if (entry.length >= instance.options.partialChars && instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.name.substr(foundPos-1,1))) {
                  partial.push(makeElem(elem, true));
                  break;
            }
          }

          foundPos = instance.options.ignoreCase ?
            elem.name.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
            elem.name.indexOf(entry, foundPos + 1);

        }
    }
    
    if (partial.length)
        ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
		
		if (ret.length == 0)
			return "<ul><li>No friends match!</li></ul>";
		else
			return "<ul>" + ret.join('') + "</ul>";		
};

// Tweaked from the onKeyPress method in Autocompleter.Local
function friendSelectorOnKeyPress(event) {
  if(this.active)
    switch(event.keyCode) {
     case Event.KEY_TAB:
     case Event.KEY_RETURN:
       chooseFriend(this.getCurrentEntry());
       this.hide();
       Event.stop(event);
     case Event.KEY_ESC:
       this.hide();
       this.active = false;
       Event.stop(event);
       return;
     case Event.KEY_LEFT:
     case Event.KEY_RIGHT:
       return;
     case Event.KEY_UP:
       this.markPrevious();
       this.render();
       Event.stop(event);
       return;
     case Event.KEY_DOWN:
       this.markNext();
       this.render();
       Event.stop(event);
       return;
    }
   else
     if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
       (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

  this.changed = true;
  this.hasFocus = true;

  if(this.observer) clearTimeout(this.observer);
    this.observer =
      setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
};

// Tweaked from the getUpdatedChoices method in Autocompleter.Local
function friendSelectorGetUpdatedChoices() {
    this.updateChoices(this.options.selector(this));
    FB.XFBML.parse($('friendList'));
}

// Helper for prettifying date times
function prettifyAll(selector) {
    $$(selector).each(function (elem) {
        // Why doesn't this work in firefox sometimes?
        var utc = elem.down('.utc').innerHTML.strip();
        elem.down('.pretty').update(prettyDate(utc));
    });
};


// Follow
function followshipButtonClick(userId) {
    var button = this;
    var action = button.readAttribute('action');
    button.update(button.innerHTML + "ing...");
    return new Ajax.Request('/users/' + userId + '/' + action + '.json', {
      method: 'post',
      onSuccess: function (transport) {
        var r = transport.responseJSON;
        if (r.success) {
          if (action === 'follow') {
            button.removeClassName('follow').addClassName('unfollow').update('Unfollow').writeAttribute('action', 'unfollow');
          } else {
            button.removeClassName('unfollow').addClassName('follow').update('Follow').writeAttribute('action', 'follow');;
          }
        }
      }
  });
};