// Copyright 2009 Foursquare Labs Inc. All Rights Reserved.
$.fn.tooltip = function(options) {
  function hasOption(option) {
    if(typeof(options) != "undefined") { return options[option] } 
    else { return undefined }
  }
  
  if($('.hoverTip').length < 2) {
    var content = '<div class="hoverTip hoverTipBottom"><div class="hoverTipInner"></div></div>'
    $('body').append(content)
  }

  var theTip = $('.hoverTip:last');
  
  this.each(function() {
    var self = $(this);  
    var title = "";
    var attribute = 'title';
    if(hasOption('useAlt') == true) { attribute = 'alt' }
    var tipWidth = 'none';
    if(hasOption('tipWidth') != undefined) { tipWidth = hasOption('tipWidth')}
    
    self.data(attribute, self.attr(attribute)).attr(attribute, "");
    self.hover(function(){
      if(self.data(attribute) != "") {
        $('.hoverTipInner:last').text(self.data(attribute));

        var tLeft = Math.ceil($(this).offset().left);  
        var tWidth = $(this).width();
        var tX = (tLeft + Math.ceil(tWidth / 2) - 31)+"px";

        var tTop = Math.ceil($(this).offset().top);  
        var topOffset = theTip.height() + 15;  
        var tY = (tTop - topOffset)+"px";

        theTip.css({'top' : tY, 'left' : tX, 'max-width' : tipWidth});
        $(theTip).show();
      }
    }, function(){
      $(theTip).hide()
    })
  })
}

jQuery.extend( jQuery.easing, {
  easeOutExpo: function (x, t, b, c, d) {
  		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
}});
  
window.fourSq = {};

// Add facebook helpers to fourSq object
(function() {
  var facebook = {
    name: function(target) {
      FB.getLoginStatus(function(response) {
        if (response.session && response.perms && $(target).length) {
          FB.api('/me', function(response) {
            $(target).attr('href', response.link).text(response.name);
          });
        }
      });
    }
  }
  
  fourSq.facebook = facebook;
})();
  
function noop(func) {
  func();
}

function approve(message, func) {
  if (confirm(message)) {
    func();
  }
}

function fadeIn(id, time, func) {
  $('#'+id).fadeIn(time)
  func();
}

function show(id, func) {
  $("#"+id).show();
  func();
}

function spinner(id, func) {
  $("#"+id).html("<div class='lazyLoad'>Loading... <img src='/img/ajax_spinner.gif' class='loading' height='32' width='32' alt='wait'/></div>");
  func();
}

function submitForm(obj) {
  while(obj.nodeName.toLowerCase() != 'form') {
    obj = obj.parentNode;
  }
  obj.submit();
}

function makeImgRollover(id) {
  $(id).hover(
    function() {
      this.src = this.src.replace('_off', '_on');
    },
    function() {
      this.src = this.src.replace('_on', '_off');
    }
  );
}

function showTab(tab) {
  $('.tabContainer').hide()
  $('#standardTabs a').removeClass('active')
  
  $('#' + tab).show()
  $('#' + tab + 'Trigger').addClass('active')
  
  return false;
}

function expandSection(element, max, min) {
  var target = $(element)
  var maxHeightVal = target.css('max-height')
  
  if(maxHeightVal.substring(0, maxHeightVal.length - 2) > min)
    target.animate({maxHeight: min}, 700)
  else 
    target.animate({maxHeight: max}, 1000)

  return false
}

function selectTab(elm, group) {
  $(group).removeClass('selected')
  $(elm).addClass('selected')
  $('.tab').hide()
  $('#' + $(elm).attr('title')).show()
  return false;
}

// User Page
var UserPage = {
  showTodos: function(todos) {
    var carrot = $("<img class='carrot' src='/img/tipsCarrot.png' />")
    
    if(todos === undefined) {
      $('#tipsList .tips').hide()
      $('#tipsList .todos').show()
      $('#tipsNav #todosTrigger').append(carrot)
      $('#tipsNav #tipsTrigger .carrot').remove()
    } else {
      $('#tipsList .tips').show()
      $('#tipsList .todos').hide()
      $('#tipsNav #todosTrigger .carrot').remove()
      $('#tipsNav #tipsTrigger').append(carrot)
    }
    
    return false
  },
  
  showTips: function() { return this.showTodos(false) },

  showSpinner: function(id, func) {
    $("#"+id).html('\
      <div id="loadingSpinner"> \
        <div class="lazyLoad tip tipContainer"> \
          Loading <img src="/img/ajax_spinner.gif" height="32" width="32" alt="wait"/> \
        </div> \
      </div> \
    ');
    func();
    return;
  }
}

// Venue Page
var VenuePage = {
  clearTip: function() {
    $('#tipText_field').val('')
    $('#tipInputError').hide()
    $('#venuePage .tipInput .url input').val('')
    $('#tipCharCount').text('')
  },
  updateTipCharCount: function() {
    var len = 200 - $('#tipText_field').val().length
    if(len < 200) {
      $('#tipCharCount').text(len)
    } else {
      $('#tipCharCount').text('')
    }
  },
  showSpinner: function(id, func) {
    $("#"+id).html('\
      <div id="loadingSpinner"> \
        <div class="lazyLoad tip tipContainer"> \
          Loading <img src="/img/ajax_spinner.gif" height="32" width="32" alt="wait"/> \
        </div> \
      </div> \
    ');
    func();
    return;
  }
} 

// Venue Stats Page
var VenueStats = {
  init: function() {
    var self = this
    $('.stats .times a').click(function() {self.selectTime(this)})
  },
  selectTime: function(elm) {
    $('.stats .times a').removeClass('selected')
    $(elm).addClass('selected')
  }
}

var Tip = {
  initTipActions:function() {
    ZeroClipboard.setMoviePath('http://foursquare.com/ZeroClipboard.swf');
    
    $('.tip .todo').live('click', function() {
      $('.hoverTip:last').hide();
      var id = $(this).closest('.tip').attr('id').substr(3)
      if($(this).hasClass('checked')) { 
        $(this).removeClass('checked').addClass('unchecked') 
        $(this).data('title', 'Add to My To-Do List');
        Tip.removeFromTodo(id)
      }
      else if($(this).hasClass('unchecked')) { 
        $(this).removeClass('unchecked').addClass('checked')
        $(this).data('title', 'Remove from My To-Do List');
        Tip.addToTodo(id)
      }
    })
    
    $('.tip .done').live('click', function() {
      $('.hoverTip:last').hide();
      var id = $(this).closest('.tip').attr('id').substr(3)
      if($(this).hasClass('checked'))
        Tip.unmarkAsDone(id)
      else if($(this).hasClass('unchecked')) { 
        if($(this).siblings('.todo').hasClass('checked'))
          Tip.removeFromTodo(id);
          
        Tip.markAsDone(id)
      }
    })
    
    $('#buttonEmbedButtons input[type=radio]').live('click', function() {
      var textArea = $('#buttonEmbedCode textarea:last')
      textArea.val(textArea.val().replace(/color=.*?\"/i, 'color=' + $(this).attr('class') + '"'));
      if(typeof(clip) != 'undefined') {
        clip.setText($('#buttonEmbedCode textarea:last').val());
      }
      $('#copyClipButton').removeClass('copied').text("COPY EMBED CODE");
    })
    $('#buttonEmbedCode textarea').live('click', function() { $(this).focus().select(); });
    
    $(document).bind('reveal.facebox', function() {
      $('#buttonEmbedButtons input').removeAttr('checked').filter('.light').attr('checked', 'checked')
      
      $('#facebox #copyClipButton').each(function() {
        clip = new ZeroClipboard.Client();
        clip.setText($('#buttonEmbedCode textarea:last').text());
        clip.glue(this);
        clip.addEventListener('onComplete', function() {
          $('#copyClipButton').addClass('copied').text("COPIED!");
        });
        
      })
    })
    
    $(document).bind('closed.facebox', function() { if(typeof clip != 'undefined') clip.destroy(); });
    
    Tip.setupToolTips();
  },
  setupToolTips: function() {
    $('.done,.todo,.doneCount,.todoCount,.tip_activity_buttons .embed,.tip_activity_buttons .delete').tooltip();
  },
  setupToolTip: function(id) {
    $('#tip' + id +' .done, #tip' + id +' .todo,.doneCount, #tip' + id +' .todoCount, #tip' + id +' .tip_activity_buttons .embed,#tip' + id +' .tip_activity_buttons .delete').tooltip();
  },
  updateTipStatus: function(id, message) {
    $('#tip' + id + ' .tipStatus').text(message).stop(true,true).fadeIn(300).delay(1200).fadeOut(200);
  },
  markAsDone: function(id) {
    countElem = $('#tip' + id + ' .doneCount .count')
    countElem.text(parseInt(countElem.text()) + 1)
    $('#tip' + id + ' .check').fadeIn(500);
    elem = $('#tip' + id + ' .done');
    elem.removeClass('unchecked').addClass('checked');
    elem.data('title', 'Undo');
    elem.siblings('.todo').removeClass('checked unchecked').addClass('disabled');
    elem.siblings('.todo').data('title', '');
    Tip.updateTipStatus(id, 'Done!')
  },
  unmarkAsDone: function(id) {
    countElem = $('#tip' + id + ' .doneCount .count')
    countElem.text(parseInt(countElem.text()) - 1)
    $('#tip' + id + ' .check').fadeOut(500);
    elem = $('#tip' + id + ' .done');
    elem.removeClass('checked').addClass('unchecked'); 
    elem.data('title', 'I\'ve done this');
    elem.siblings('.todo').removeClass('disabled').addClass('unchecked');
    elem.siblings('.todo').data('title', 'Add to My To-Do List');
    Tip.updateTipStatus(id, 'Undone!')
  },
  updateTodoListButton: function(id, className) {
    $('#tip' + id + ' .todo').removeClass("unchecked checked disabled").addClass(className)
  },
  updateDoneButton: function(id, className) {
    $('#tip' + id + ' .done').removeClass("unchecked checked").addClass(className)
  },
  addToTodo: function(id) {
    Tip.updateTipStatus(id, 'Added!')
    $('#tip' + id + ' .dogear').css({
      'right' : '-22px',
      'display' : 'block'
    }).animate({
      right: '+=22'
    }, 500, 'easeOutExpo')
  },
  removeFromTodo: function(id) {
    Tip.updateTipStatus(id, 'Removed!')
    $('#tip' + id + ' .dogear').animate({
      right: '-=22'
    }, 500, 'easeOutExpo')
  },
  showEmbed: function(id, type) {
    if(typeof(id) == 'object') { id = $(id).closest('.tip').attr('id').substr(3); }
    
    switch(type) {
      case 'tip': 
        key = 'tid';
        break;
      case 'venue':
        key = 'vid';
        break;
      default:
        key = 'tid';
        break;
    }
    
    // Reset styles
    $('#copyClipButton').removeClass('copied').text("COPY EMBED CODE");
    
    var url = 'http://' + window.location.host + '/button.html?'+key+'='+id+'&color=light';
    var embed = "<iframe src=\"" + url + "\" allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" style=\"width:165px; height:25px;\"></iframe>";
    
    $('#buttonEmbedTemplate textarea').text(embed);
    $.facebox({ div: '#buttonEmbedTemplateContainer' });
  },
  showVenueTodo: function() {
    $('#venueTodoPopup textarea').val('Add a note (optional)').addClass('default');
    $('#venueTodoPopup .count').hide();
    $.facebox({ div: '#venueTodoPopup' });
  },
  addVenueToToDo: function() {
    jQuery(document).trigger('close.facebox');
    $('.addVenueToToDoList').addClass('success');

    if($('.venueDogear').css('display') != 'block') {
      $('.venueDogear').data('title', 'You have 1 To-Do here');
      $('.venueDogear').css({
        'right' : '-24px',
        'top' : '-24px',
        'display' : 'block'
      }).animate({
        right: '+=24',
        top: '+=24'
      }, 500, 'easeOutExpo')
    }
  }
}

var ManageFriends = {
  init: function() {
    $(function() {
  
      // Hide the New Friend Requests module
      $('#HideThisSession a').click(function() {
        var container = $('#NewFriendRequests');
        if(!container.hasClass('hidden')) {
          container.addClass('hidden');
          $(this).text('Show')
        } else {
          container.removeClass('hidden');
          $(this).text('Hide')
        }
        return false;
      });
      
    })
    
  }
}

function makeStatelessCall(url) {
  $.ajax({'url': url,
          'type': 'POST',
          'dataType': 'script'})
}

