function showFlash(message) {
	$.scrollTo("#header", 400, { onAfter: function() {
		if (!$("#flag-flash-message").length > 0 ) {
			$("<div id=\"flag-flash-message\" class=\"flash success\">" + message + "</div>").fadeIn("slow").insertAfter("#flash-message-hook");
		};
	}});
}

jQuery(document).ready(function($) {
    $("#content-column > .flash .close, #header-simple > .flash .close").click(function() {
      if($.browser.msie && $.browser.version == '7.0') {
        $(this).hide();
      }
      
      $(this).closest('.flash').slideUp();
    });
});

var Advicetap = {};

Advicetap.flagObject = function(link, args) {
	$.post("/flags", args );
	showFlash('Thank you, Flag submitted');
	$(link).hide();
}

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

$.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;


$(document).ready(function() {	
	// Global search
	$('#global-search-form').submit(function(){
		var form = $(this);
		form.attr('action', $('#global-search-type-dropdown').val());
		form.submit();
		return false;
	})
});

// Importing Contacts
$(document).ready(function(){
	// Hijak form and submit via AJAX
	$("#get-contacts-form").submit(function(){
		var form = $(this);
		var submitButton = $(form.find("input[type=submit]")[0]);
		var spinner = form.find(".spinner");
		
		// Change Button to Getting Contacts...
		var originalSubmitText = submitButton.attr("value");
		submitButton.attr("value", "Getting Contacts...");
		
		// Close any Errors
		form.find('.form-errors').remove();
		
		// Show spinner
		spinner.show();
		
		var formValues = form.serialize();
		
		// Disable form
		form.find("input").attr("disabled", true);
		
		$.post(form.attr("action"), formValues, function(data, status){
			$(".returned-contacts").remove(); // remove any existing contacts on the screen
			form.after(data);
			form.find("input").attr("disabled", false);
			submitButton.attr("value", originalSubmitText);
			spinner.hide();
		}, 'html');
		return false;
	});
});


// Home Page Status updates
$(document).ready(function(){
	
	// When the Update Status button is pressed
	$("#new_status").submit(function(){


		// If the status content input ISNT empty
		if(!$("#status_content").val() == "") {
		
			var spinner = $(this).find(".spinner");

			// Show the spinner to tell the user that their status is being updated
			spinner.show();

			// Take the forms action (creating a status) and do it via AJAX
			$.post(this.action, $(this).serialize(), function(data){

				// When the status is done updating
				// Remove the disabed attribute from the update status form
				inputs.removeAttr("disabled")
				// Remove the spinner
				spinner.hide();
				// Remove the status the user typed in the text input
				$("#status_content").val("");

			}, "script");

			// Disable the inputs while the AJAX is happening
			var inputs = $(this).find("input").attr("disabled", true);
		
		}
		
		// Dont return anything
		return false;
	});

	// Remove the action from the clear-status-link because this will be done by AJAX
	$('a#clear-status-link').removeAttr('onclick');
	
	// When the clear-status-link is clicked
	$('a#clear-status-link').live('click', function() { 
		// Fade Out and remove the current status
		$("#current-status").fadeOut('slow', function() {
			$("#current-status").remove;
		});
		
		// Take the links href (clearing the status) and do it via AJAX
		$.post(this, null, null, "script");
		
		// Dont return anything
		return false;
	});

});

// Home Page Status Character Restriction
jQuery(document).ready(function($) {
    // Assigns default value to search field
    $("#status_content").DefaultValue("What’s On Your Mind?");
    $("#status_content").focus(function(){
        $(this).addClass('large');
    });
    $("#status_content").blur(function(){
      // Add a bit of a delay so that this edge case will work:
      // 1) #status_content has focus
      // 2) click on #clear-status-link
      // The blur event runs, shrinks #status_content, and the click event is ignored 
      // since the mouse cursor is no longer hovering over #clear-status-link
      var $this = $(this);
      setTimeout(function() {
        $this.removeClass('large');
      }, 80);
    });
    $("#status_content").keypress(function (e) {
        if($(this).val().length > 140)
        {
            $("#update_status_button").attr("disabled","disabled");
        }
        else
        {
            $("#update_status_button").removeAttr("disabled");
        }
    });
    
  function limitChars(textid, limit, infodiv) {
    var text = $('#'+textid).val();
    var textlength = text.length;
    if(textlength > limit)
      {
        $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
        $('#'+textid).val(text.substr(0,limit));
        return false;
      }
    else
      {
        $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
        return true;
      }
  }
  
  $(function(){
    $('#status_content').keyup(function(){
        limitChars('status_content', 140, 'charlimitinfo');
    })
  });

});







// Welcome Message
$(document).ready(function(){
	$("#welcome-message-close").click(function(){
		$(this).closest("#welcome-message").fadeOut("slow");
		$.post("/close_welcome_message", {from: window.location.pathname});
		return false;
	})
})

// Some "last-child" fixes
$(document).ready(function(){
	$("#status-replies .comments-bubble-body .comment:last-child, ul.result-item-list li.result-list-item:last-child").addClass("last-child")
	$("ul.result-item-list li.result-list-item:last-child").css({"background": "#FFFFFF"})
})

// Spinners should appear when the form is submitting
$(document).ready(function() {
  $('.spinner').each(function() {
    $(this).closest('form').submit(function() {
      $(this).find('.spinner').show();
    });
  });
});



if(typeof CKEDITOR !== 'undefined')
  CKEDITOR.config.customConfig = '';  

ckeditorize = function(element, options, optional_callback) {
  if(!element || element.size() == 0)
    return;
  
  var element = $(element);
  var default_options = {
    skin: 'v2',
    toolbar: 'Minimal',
    toolbar_Minimal:
    [
        ['Bold', 'Italic', 'Underline', 'NumberedList', 'BulletedList']
    ],
    contentsCss: '/stylesheets/ckeditor_iframe.css'
  };
  
  options = $.extend(default_options, options);
  
  
  // Make it easy to change styles on focus with a .focus css selector
  // Except in IE7 since it doesn't support the :focus pseudo selector
  var setup_focus = function() {
    if(!($.browser.msie && $.browser.version == '7.0')) {
      var editor = element.ckeditorGet();
      editor.on('focus', function(e) {
        $(e.sender.container.$).addClass('focus').find('iframe').contents().find('body').addClass('focus');
      });
      
      editor.on('blur', function(e) {
        $(e.sender.container.$).removeClass('focus').find('iframe').contents().find('body').removeClass('focus');
      });
    }
  }
  
  var callback = function() {
    setup_focus();
    if(optional_callback != null)
      optional_callback(element.ckeditorGet());
  }
  
  element.ckeditor(callback, options);
};



$(function() {
  // In logged out pages...
  // Ensure vertically centered text in form field in Firefox 3.5
  // Firefox 3.5: "1.9.1.9"
  // Firefox 3.6: "1.9.2.3"
  if($('body.simple').length > 0 && $.browser.mozilla) {
    var version = $.browser.version.split('.');
    if(version[0] <= 1 &&  version[1] <= 9 && version[2] <= 1) {
      $('input[type=text], input[type=password]').css({'padding-top': '7px', 'padding-bottom': '1px'});
    }
  }
});




$(function() {
  $('.sugar input').focus(function() {
    $(this).blur();
  });
});