//preload the ajax spinner 
var bf_ajax_spinner = new Image();
bf_ajax_spinner.src = "/images/global/ajax-loader.gif";
var bf_spinner = "<img src=" + bf_ajax_spinner.src + " class='spinner' />"

function _ajax_request(url, data, callback, type, method) {
  if (jQuery.isFunction(data)) {
    callback = data;
    data = {};
  }
  return jQuery.ajax({
    type: method,
    url: url,
    data: data,
    success: callback,
    dataType: type
  });
}

jQuery.extend({
  destroy: function(url, data, callback, type) {
    return _ajax_request(url, data, callback, type, 'DELETE');
  },
  put: function(url, data, callback, type) {
    return _ajax_request(url, data, callback, type, 'PUT');
  }
});

// same as jQuery $, but expects elements to be found
// throw an exception if no elements are found
// give alert also if in development environment
$_ = function(arg1, arg2) {
  function isDevelopmentEnvironemnt(){
    return window.location.href =~ /http:\/\/localhost/
  }

  var selected = jQuery(arg1, arg2);
  if( !selected.length ) {
    message = arg2 ?  "expected '$('" + arg1 + "','" + arg2 + "') to match something"
                   : "expected '" + arg1 + "' to match something"
    if( isDevelopmentEnvironemnt() ){ alert(message); }
    throw message;
  }
  return selected;
}


$(function(){
	// http://dev.jquery.com/ticket/6359
	var originalLive = jQuery.fn.live;
  jQuery.fn.live = function(types) {
    var self = this;
    var args = arguments;
    if (types == 'click') {
      setTimeout(function() {
          originalLive.apply(self, args);
      }, 0);
    } else {
      originalLive.apply(self, args);
    }
  };
  
  $('.button-container').one("click", function() {
    $(this).children().click();
  });
	
  $('.not_implemented').live('click', function(){
    alert('Featured not yet implemented');
    return false;
  })
  
  // short-circuits 'more' links unless if we have a valid URL or are in an sf-menu
  $('a.more').click(function(){
    if($(this).attr('href') == '#' && $(this).closest('.sf-menu').size() == 0) {
	    return false;
	  }
  })
  
  // binds to any form with a class of 'post'
  $('form.post').live('submit', function(){
    $.post($(this).attr('action'), $(this).serialize(), null, "script");  
    return false;
  });

  // binds to any form with a class of 'destroy'
  $('form.destroy').live('submit', function(){
    $.destroy($(this).attr('action'), $(this).serialize(), null, "script");  
    return false;
  });
  
  // binds to any form with a class of 'put'
  $('form.put').live('submit', function(){
    $.put($(this).attr('action'), $(this).serialize(), null, "script");
    return false;
  });
  
  // binds to any link with a class of 'get'
  $('a.get').live('click', function() {
    $.get($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });

  // binds to any link with a class of 'delete'
  $('a.destroy').live('click', function() {
    $.destroy($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  });
  
  // binds to any link with a class of 'post'
  // assumes an HTML5 attribute called 'data-token' exists, which is used for authenticity tokens
  $('a.post').live('click',function(){
    $.post($(this).attr('href'), "authenticity_token=" + $(this).attr('data-token'), null, "script");  
    return false;
  });
  
  // appends or removes an 'active' class for any element with a 'toggle' class
  // useful for other functions that need to interogate the element's current state
  // as well as binding css styles
  $('a.toggle').live('click', function(){
    $(this).toggleClass('expanded');
  });
  
  // initialize static drop down menus
  BF.sf();
  
  // TODO: div.closeOut not active link
  // TODO: li click off menu very ungraceful in IE
  // TODO: transparent PNG loses transparency on fadeOut in IE 
  $("div.outerMenuDropped").each(function(){
    $(this).css("height", $(this).height() + "px");
  });
  $("div.outerMenuDropped").hide();
  $("div.megaMenu #megaMenuLink").click(function(){
    var body = $(this).parents('.megaMenu').children("div.outerMenuDropped");
    var closeLink = $(this).parent().children("div.outerMenuDropped .closeOut a");
    if(body.is(":hidden")) {
      body.slideDown("800");
      $('div.megaMenu .closeOut a').show();
      $('div.megaMenu #megaMenuLink').addClass('expanded');
    } else {
      body.slideUp("slow");
      $('div.megaMenu .closeOut a').hide();
      $('div.megaMenu #megaMenuLink').removeClass('expanded');
    }
  });
  $('div.megaMenu').children('li').mouseup(function(){
    var body = $(this).parent().children('div.outerMenuDropped');
      body.fadeOut('slow');
      return false;
  });
  $('div.megaMenu .closeOut a').click(function(){
    $(this).hide();
    $('div.outerMenuDropped').slideUp('slow');
    $('div.megaMenu #megaMenuLink').removeClass('expanded');
    return false;
  });
  $('body').click(function() {
    $('div.megaMenu .closeOut a').click();
  });
  $('div.megaMenu').click(function(event){
    event.stopPropagation();
  });
  
  BF.Tooltip.bind('a.tooltip');
  
  $('.talk-to-birdfellow a').click(function() {
  	$(this).parents('div').children('p.submit-message').hide(); 
    $(this).parents('div.talk-to-birdfellow').children('form').slideToggle();   
    return false;
  });
  
  $('.talk-to-birdfellow form input[type=reset]').click(function() {
    $(this).parents('div').children('form').slideToggle(); 
    return false;
  });
  
  $('#flash-messages').fadeIn(1500, function(){
    setTimeout(function() {
      $("#flash-messages").fadeOut("slow");
    }, 2000);
  });
  
  // turns one or more linked images with a selector of 'zoomable'
  // into a lightbox-based slideshow
  $('a.slideshow').live('click', function(){
    BF.Lightbox.bind('a.zoomable');
    $('a.zoomable').first().trigger('click');
    return false;
  });

  $('.horizontalNav .view-items-text-only').live('click', function() { 
    $(this).parents('.tabs').children('li').removeClass('active');
    $(this).parents('.tabs').children('li a').removeClass('selected');
    $(this).parents('li').addClass('active');
    $(this).addClass('active');
    $('.item-container').removeClass('detailed-view'); 
    $('.item-container').addClass('text-view'); 
    return false;
  });
  
  $('.horizontalNav .view-items-with-details').live('click', function() { 
    $(this).parents('.tabs').children('li').removeClass('active');
    $(this).parents('.tabs').children('li a').removeClass('selected');
    $(this).parents('li').addClass('active');
    $(this).addClass('active');
    $('.item-container').addClass('detailed-view'); 
    $('.item-container').removeClass('text-view'); 
    return false;
  });
  
  $('.sf-menu.header').hover(function() {
    if($(this).children('li').outerWidth(true) > '215') {
      $(this).addClass('long');
    } else {
      $(this).removeClass('long');      
    }
  });
})

var BF = {};

// Renders prettier tooltips 
// set the 'title' attribute of your element
// relies on jquery.qtip
BF.Tooltip = {
  bind: function(target) {
    $('a.tooltip').live('mouseover', function() {
      if ($(this).data('qtip')) { return false; }
      $(this).qtip({
        overwrite: false,
        show: {
         ready: true
        },
        position: {
          corner: {
            target: 'topMiddle',
            tooltip: 'bottomMiddle'
          }
        },
        style: { 
          name: 'normal',
          width: 194
        }
     }); 
   });
  }
}

// Custom qTip Styles

$.fn.qtip.styles.normal = {
  tip: true,
  background: '#FFF799',
  color: '#5A5E68',
  fontSize: '11px',
  border: {
    width: 2,
    radius: 3,
    color: '#DACA2C'
  },
  padding: 10
}

$.fn.qtip.styles.userInfo = {
  background: '#FFF799',
  color: '#5A5E68',
  fontSize: '11px',
  width: 244,
  border: {
    width: 2,
    radius: 3,
    color: '#DACA2C'
  },
  tip: 'bottomMiddle'
}

$.fn.qtip.styles.side = {
 tip: true,
  background: '#FFF799',
  color: '#5A5E68',
  fontSize: '11px',
  border: {
    width: 2,
    radius: 3,
    color: '#DACA2C'
  },
  padding: 9,
  width: 194
}

$.fn.qtip.styles.sideTop = {
 tip: true,
  background: '#FFF799',
  color: '#5A5E68',
  fontSize: '11px',
  border: {
    width: 2,
    radius: 3,
    color: '#DACA2C'
  },
  padding: 10,
  width: 194
}

BF.sf = function(selector) {
	if (selector == undefined) {
		selector = '';
	}
	$(selector + ' ul.sf-menu').superfish({
	  autoArrows: false
	});
};

// Returns a URL with the anchor removed from it
BF.cleanUrl = function(url) {
	return(url.split("#")[0]);
}

BF.dialogRequiresField = function(fieldSelector, buttonSelector, buttonIndex) {
	// Tie the submit button to the text field
	$(fieldSelector).keyup(function(){
		// Need locals here in case we swap out the dialog box contents
		var targetField = $(fieldSelector);
		var btn = $(buttonSelector).eq(buttonIndex);
		
		if (targetField.val().length > 0) {
			btn.removeAttr('disabled');
			btn.removeClass('disabled');
		}
		else {
			btn.attr('disabled', 'disabled');
			btn.addClass('disabled');
		}
		
		return(true);
	});
	
	// Invoke the event to initialize the proper state
	$(fieldSelector).keyup();
}

BF.flashMessage = function(message) {
	if ($('#flash-messages').size() < 1) {
    $('#contentWrapper').prepend("<div id='flash-messages' style='display:none'></div>");
  }
  $('#flash-messages').html("<p><span>"+message+"</span></p>");
  $('#flash-messages').fadeIn(1500, function(){
    setTimeout(function() {
      $("#flash-messages").fadeOut("slow");
    }, 2000);
  });
}

BF.uiDialogRequiresField = function(fieldSelector, buttonSelector, buttonIndex) {
	// Start out in a disabled state
	$(buttonSelector).eq(buttonIndex).attr('disabled', 'disabled').addClass('ui-state-disabled');
	
	// Tie the submit button to the text field
	$(fieldSelector).keyup(function(){
		// Need locals here in case we swap out the dialog box contents
		var targetField = $(fieldSelector);
		var btn = $(buttonSelector).eq(buttonIndex);
		
		if (targetField.val().length > 0) {
			btn.removeAttr('disabled');
			btn.removeClass('ui-state-disabled');
		}
		else {
			btn.attr('disabled', 'disabled');
			btn.addClass('ui-state-disabled');
		}
		
		return(true);
	});
}

// prevent disabled form buttons from working in IE
$('input[disabled]').live('click', function() { 
  return false;
});

// used for secondary nav behavior
// currently assumes a specific markup structure
BF.Tab = {
  bind: function(tabs) {
    $(tabs.selector).click(function() { 
      BF.HashHistory.save(tabs.getSelectedHref(this));      
      return tabs.animate(this);
    });
    
    // Select tab when document.location.hash changes
    BF.HashHistory.onChange(BF.Tab.select(tabs));
  },
  select: function(tabs) {
    var url = BF.HashHistory.extract();
    $(tabs.selector).each(function(){
      if(url.length > 0 && tabs.getSelectedHref(this).match(url+'$') == url) tabs.animate(this);
    });
  }
}

// (de)serializes url info for use with AJAX/in-page nav
// relies on jQuery BBQ lib
BF.HashHistory = {
  save: function(href) {
    // persists url as hashtag
    $.bbq.pushState('#' + href);
  },
  extract: function() {
    return $.param.fragment();
  },
  onChange: function(callback) {
    $(window).bind('hashchange', function() { callback });    
  },
  listenForChanges: function() {
    $(window).trigger('hashchange');
  }
}

// General sharing JS class
BF.Sharing = {
	init: function() {
    var expanded = false; 
    $(".share-dialog #message a.more").click(function() {
      if (expanded == false) {
        $('.share-dialog #message a.more').html('hide message'); 
        expanded = true;
      } else {
        $('.share-dialog #message a.more').html('show message'); 
        expanded = false;
      }
      $(this).toggleClass('expanded');
      $(".share-dialog #message textarea").slideToggle();
      return false;
    });

    $('#share_name').autocomplete({serviceUrl: '/connections/autocomplete', width: '350'});

    BF.Sharing.checkLimits();
	},
	
	addEmail: function() {
		var url = this.formUrl() + '_email';
		var params = 'email=' + $('#share_email').val();
		$.get(url, params, null, 'script');
		return(false);
	},

	addMember: function() {
		var url = this.formUrl() + '_name';
		var params = 'name=' + $('#share_name').val();
		$.get(url, params, null, 'script');
		return(false);
	},
	
	checkLimits: function() {
		var emailListSize = $('#share-email-list li').size();
		var memberListSize = $('#share-member-list li').size();
		
		// Check email limits
		if (emailListSize > 3) {
			$('#share-email-fields').hide();
		}
		else {
			$('#share-email-fields').show();
		}
		
		// Check member limits
		if (memberListSize > 3) {
			$('#share-member-fields').hide();
		}
		else {
			$('#share-member-fields').show();
		}
		
		// Check button status
		var btn = $("#dialogBox input[type='submit']");
		if (emailListSize > 0 || memberListSize > 0) {
			btn.removeAttr('disabled');
			btn.removeClass('disabled');
		}
		else {
			btn.attr('disabled', 'disabled');
			btn.addClass('disabled');
		}
	},
	
	formUrl: function() {
		return $('#dialogBox form').attr('action');
	},
	
	remove: function(link) {
		$(link).closest('li').remove();
		BF.Sharing.checkLimits();
		return(false);
	},
	
	shareType: function(shareType) {
		if (shareType == 'email') {
			$('#share-member-list').html('').show();
			$('#share_type_email_label').addClass('selected');
			$('#share_type_member_label').removeClass('selected');
			$('#share-member').hide();
			$('#share-email').show();
		}
		else {
			$('#share-email-list').html('').show();
			$('#share_type_member_label').addClass('selected');
			$('#share_type_email_label').removeClass('selected');
			$('#share-email').hide();
			$('#share-member').show();
		}
	}
}

// encapsulates 3rd party lightbox component
BF.Lightbox = {
  bind: function(target, options) {    
    this.options = {
      hideOnOverlayClick: true,
      hideOnContentClick: true,
      showNavArrows:      false,
      enableEscapeButton: true
    };
    
    if (options) { $.extend(this.options, options); }
    $(target).fancybox(this.options);
  }
}
