// Enable Prototype compatibility mode for jQuery
jQuery.noConflict();

// Make jQuery play nice with respond_to blocks
/*jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})*/

jQuery(document).ready(function() {
  jQuery(document).trigger('redrover_ready');
});

jQuery(document).bind("redrover_ready", function(){
  jQuery.fn.fancybox.defaults.onComplete = function(){
    jQuery(document).trigger('redrover_ready');
  }

  jQuery("a.close-fancybox").click(function(){
    jQuery("#fancybox-close").click();
  });

	if(jQuery('body').hasClass('facebook-enabled')) {
	  var boxwidth = 755;
	} else {
	  var boxwidth = 430;
	}

  jQuery("a#loginHere").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': boxwidth, 'height': 460, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false });
	jQuery("a#signupBtn").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 650, 'height': 460, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false });
	jQuery("a#introBtn").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 440, 'height': 340, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false });
	jQuery("a#signupBtn").click(function(){
	  pageTracker._trackPageview('/users/signup_lightbox');
	});
	
  jQuery("a.fancy-lightbox").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 620, 'height': 300, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false});
  jQuery("a.fancy-lightbox-terms").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 820, 'height': 550, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false});
	jQuery("a.fancy-lightbox-email").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 620, 'height': 400, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false});
	jQuery("a#group_links").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 620, 'height': 300, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false}); 
	
	apply_fancy_add();
	apply_start_group();

  jQuery('a.ajax-delete').live('click', function() {
    var title = jQuery(this).attr('title');
    var do_delete = true;
    if(title.length > 0){
      do_delete = confirm(title);
    }
    if (do_delete){
      jQuery.post(this.href, { _method: 'delete', format: 'js' }, null, "script");
    }
    return false;
  });

  jQuery('a.ajax-update').live('click', function() {
    jQuery.post(this.href, { _method: 'put', format: 'js' }, null, "script");
    return false;
  });

  jQuery('a.ajax').live('click', function() {
    jQuery.get(this.href, { format: 'js' }, null, "script");
    return false;
  });
	jQuery('a.ajax_show_on_load').show();

  jQuery(".submit-form").click(function() {
    jQuery(this).parent('form').submit();
  });

  apply_ajax_forms();

  jQuery('a.dialog-pop').live('click', function() {
    var d = jQuery('<div class="dialog"></div>').appendTo("body");
    d.dialog({ modal: true, autoOpen: false, width: 'auto', title: jQuery(this).attr('title') });
    d.load(jQuery(this).attr('href'), '', function(){
      d.dialog("open");
      apply_ajax_forms();
    });
    return false;
  });

  jQuery(".submit-delete").live('click', function() {
    jQuery(this).parents('.delete-container').fadeOut();
    var form = jQuery(this).parents('form');
    jQuery.post(form.attr('action') + '.json', form.serialize(),
      function(data){
        var json = eval('(' + data + ')');
        if(!json.success){
          jQuery.jGrowl.info(json.message);
        }
      });
    return false;
  });
  
  jQuery(".submit-delete-js").live('click', function() {
    jQuery(this).parents('.delete-container').fadeOut();
    var form = jQuery(this).parents('form');
    jQuery.post(form.attr('action') + '.js', form.serialize(),
      function(data){
      });
    return false;
  });

  jQuery('.waiting').hide();
  jQuery(".wait-button").live('click', function() {
    jQuery(this).siblings('.waiting').show();
    jQuery(this).hide();
  });

  // Applies overlabels (grey helper text inside form fields) to fields that have a label
  // tag with the class "overlabel" and are inside a div with the class "overlabel-wrapper".
  jQuery("label.overlabel").overlabel();
  
  // Focus on a field in a form with the class "focus" applied to it
  jQuery(".focus").livequery(function(){
    jQuery(this).focus();
  });

  // Close tag popup if they click outside of it.
  //jQuery('#overlay_modal').livequery('click', function() {
  //  TagPopup.hideTagWindow(); 
  //});
  jQuery('body').click(function(event) {
    TagPopup.hideTagWindow(); 
  });
  jQuery('.dialog').livequery('click', function(event) {
    event.stopPropagation();
  });
  
  // Bind to the perPage form's submit and cause it to perform an ajax submit
  jQuery('form.perPage').submit(function(){
    jQuery(this).ajaxSubmit({target: '#group_members_container'});
    jQuery('#group_members_container').fadeIn();
    return false;
  })
  
  // Make the perPage form submit whenever the change callback is used
  jQuery('form.perPage').change(function(){
    jQuery(this).get(0).submit();
  });
  
  // Ajax-ify any pagination links
  jQuery('div#paginated_div .paginate a').livequery('click', function(){
    jQuery('#paginated_div').load(this.href);
    return false;
  });
  
    jQuery('.truncateMe').truncate({
      max_length: 200,
      more: "more..."
    });

  jQuery('#filter_user_type_options li:first').addClass("first");
  jQuery('#filter_user_type a:first').click(function() {
    $filterTrigger = jQuery('#filter_user_type');
    $ul = jQuery('#filter_user_type_options');
    if ($ul.css('display') == 'none') { 
      $filterTrigger.css('width','150px');
      $ul.slideDown('fast'); 
    }
    else { 
      $ul.slideUp('fast', function() {
        $filterTrigger.css('width','auto');
      }); 
    }
    return false;
  });

  jQuery('#filter_user_type ul a').click(function() {
    jQuery('#filter_user_type a:first').click().html('<img src="/images/spinner.gif" alt="" />');
    return true;
  });
});

function apply_ajax_forms() {
  jQuery('form.ajax').ajaxForm({
    dataType: 'script',
    beforeSend: add_headers
  });
	jQuery('form.ajax').append('<input type="hidden" name="format" value="js" />');
}

function add_headers(xhr){
	xhr.setRequestHeader("Accept", "text/javascript");
	xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}

// Hack to get around Safari not supporting the Date.now function
if (!Date.now) {
  Date.now = function () {
    return (new Date).getTime(); 
  }; 
}

//**************************************************
// Groups
//
// Displays content using the supplied selector using jQuery's slideDown effect
// and then scrolls to that element on the page in the slideDown callback using 
// the jQuery scrollTo plugin.
function showAndScrollTo(selector) {
  jQuery(selector).slideDown(function(){
    jQuery.scrollTo(selector, {duration: 400});
  });
}

function toggleTagMatchTags(selector) {
  var selector_id = selector.split("_").last();
  jQuery(selector).slideToggle("fast");
  jQuery("#tagMatchToggle_" + selector_id).toggleClass("expanded");
}

function apply_start_group(){
  jQuery("a.start_new_group").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 620, 'height': 620, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false});
}

function apply_fancy_add(){
	jQuery("a.fancy-add").fancybox({
	  'zoomSpeedIn': 0, 
	  'zoomSpeedOut': 0, 
	  'width': 730, 
	  'height': 450, 
	  'hideOnContentClick': false, 
	  'autoScale': false, 
	  'autoDimensions': false
	});
}

function apply_fancy_tag_popup(){
	jQuery("a.edit_or_flag").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'width': 620, 'height': 300, 'hideOnContentClick': false, 'autoScale': false, 'autoDimensions': false});
}

//**************************************************
// Weblinks
//

// Used in the Add / Edit Link lightbox to populate the URL and Name
// field in the form when you click on the Edit link of an existing
// link.
function populateLinkEditFields(weblink_id) {
  var url = jQuery('#lbox_weblink_'+weblink_id).attr('href');
  var name = jQuery('#lbox_weblink_'+weblink_id).html();
  
  jQuery('#weblink_name').val(name);
  jQuery('#weblink_url').val(url).focus();
}


//**************************************************
// Tags
//

function link_for_tag(tag_id) {
  if (jQuery('#tag_link_' + tag_id).length > 0) {
    return jQuery('#tag_link_' + tag_id);
  }
  else if (jQuery('#tagmatch_link_' + tag_id).length > 0) {
    return jQuery('#tagmatch_link_' + tag_id);
  }
  else {
    return null;
  }
}


function user_has_tag(tag_id) {
  if ($('tag_link_' + tag_id)) {
    $('tag_link_' + tag_id).removeClassName('red');
	$('tag_link_' + tag_id).addClassName('blue');
  }
  if ($('tagmatch_link_' + tag_id)) {
    $('tagmatch_link_' + tag_id).removeClassName('red');
	$('tagmatch_link_' + tag_id).addClassName('blue');
  }
}

function user_has_not_tag(tag_id) {
  if ($('tag_link_' + tag_id)) {
    $('tag_link_' + tag_id).removeClassName('blue');
	$('tag_link_' + tag_id).addClassName('red');
  }
  if ($('tagmatch_link_' + tag_id)) {
    $('tagmatch_link_' + tag_id).removeClassName('blue');
	$('tagmatch_link_' + tag_id).addClassName('red');
  }
}

//**************************************************
// Tag Popup
//
jQuery(document).bind('redrover_ready', function(){
	jQuery(".tag-popup").click(function() {
		var link = jQuery(this);
	  var pos = link.position();
		// Page scroll offsets
		var scrollOffsetX = jQuery(document).scrollLeft();
		var scrollOffsetY = jQuery(document).scrollTop();
		// Mouse click x,y coords with offset for popup
		var clickX = pos.left + link.outerWidth() + 10 - scrollOffsetX;
		var clickY = pos.top - 40 - scrollOffsetY;
		// Mouse click x,y coords with offset for popup
		// var clickX = pos.left + link.outerWidth();
		// 	  var clickY = pos.top - (link.outerHeight()/2);
	  // Get the ID from the element and call the function to show the popup
		var tag_id = this.id.split("_").last();
	  TagPopup.showTagWindow(tag_id, clickX, clickY);
	  return false;
	});
});

var TagPopup = {
  showTagWindow: function(tag_id, offsetX, offsetY) {
    Dialog.closeInfo();
    Dialog.info({ url: "/tags/"+tag_id+"/popup", options: { method: 'get' } }, 
                { modal: false,
                  top: offsetY, 
                  left: offsetX, 
                  recenterAuto: false, 
                  showEffectOptions: { duration: 0.2 }, 
                  hideEffectOptions: { duration: 0.2 }, 
                  width: 280, 
                  height: 210 });
  },
  hideTagWindow: function() {
    Dialog.closeInfo();
  }
}

//**************************************************
// Tag Textarea Insertion
//

var TagInput = {
  toggle: function(tag, input_id, anchor) {
    var anchor = $(anchor);
    if (anchor.hasClassName('subscribe')) {
      this.remove(tag, input_id, anchor);
    } else {
      this.add(tag, input_id, anchor);
    }
    anchor.blur();
  },
  add: function(tag, input_id, anchor) {
    var input = $(input_id);
    if(input.type != 'hidden'){ input.focus(); }

    // If the input is not empty and doesn't end with a comma add one
    if (input.value.strip().length > 0 && input.value.search(/,\s*$/) == -1) {
      input.value += ", "
    }
    input.value += tag;

    anchor.addClassName('subscribe');
  },
  remove: function(tag, input_id, anchor) {
    var input = $(input_id);
    var only_tag_regex = new RegExp("^"+tag+"$");
    var first_tag_regex = new RegExp("(^\\s*|^)"+tag+"\\s*,\\s*");
    var middle_tag_regex = new RegExp("(,\\s*)"+tag+"\\s*,\\s*");
    var trailing_tag_regex = new RegExp(",\\s*"+tag+"\\s*$");
    
    input.value = input.value.gsub(first_tag_regex, '').gsub(middle_tag_regex,', ').gsub(trailing_tag_regex, '').gsub(only_tag_regex, '');
    anchor.removeClassName('subscribe');
  }
}



//**************************************************
// Row Striping Update
//

// Called after an item is deleted from a table with row
// striping to make sure the odd/even class assignments
// are correct.
function update_row_striping(container_element) {
  container_element = $(container_element);
  counter = 0;
  children = container_element.immediateDescendants();
  children.each (function (e) {
    e.removeClassName("even");
    e.removeClassName("odd");
    if ( counter % 2 ) {
      e.addClassName("even");
    } else {
      e.addClassName("odd");
    }
    counter++;
  });
}



//**************************************************
// Weblinks
//

function observe_weblink_form() {
  $('weblink_name').observe('keypress', function(event) {
      if(event.keyCode == Event.KEY_RETURN) {
        event.returnValue = false;
        if (event.preventDefault) event.preventDefault();
        add_weblink();
      }
  });
  $('weblink_url').observe('keypress', function(event) {
      if(event.keyCode == Event.KEY_RETURN) {
        event.returnValue = false;
        if (event.preventDefault) event.preventDefault();
        add_weblink();
      }
  });
}

function add_weblink() {
  new Ajax.Request('/groups/73147891/add_weblink', {asynchronous:true, evalScripts:true, method:'post', parameters:'weblink[name]='+$F('weblink_name')+'&weblink[url]='+$F('weblink_url')});
}



//**************************************************
// Categories
//

function add_new_category(default_categories) {
  jQuery.get('/admin/categories/new.js', function(json_response){
    jQuery('#tableContent_categories').append(json_response);
    update_row_striping('tableContent_categories');
    jQuery('#tableContent_categories div.category_fields:last input:first').focus();
  });
}

function remove_category(element_id) {
  $(element_id).remove();
  update_row_striping('tableContent_categories');
}

