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

  $('#post_photo_uuid').change(function(){
    $('#post_has_rights').attr('checked', false);
  });

  $('#saveAndAddNewButton').click(function(event) {
    event.preventDefault();
    $('#saveAndAddNewField').val('true');
    $('#postsForm').submit();
  });

	$("#browseForm, .pagination a")
		.live("ajax:beforeSend", function() { $("#postsList").fadeTo('fast', 0.25); })
		.live("ajax:complete", function() { $("#postsList").fadeTo('fast', 1); });

	$('.actionButton').live('ajax:beforeSend ajax:complete', function() {
		$(this).toggleClass('loading');
	});

	$('.statsBoxes .watermark').live('click', function(event) {
		event.preventDefault();
	});

	// Utility function for toggling default text in input fields
	$('.placeholderInput')
		.val(function() {
			if($(this).val() === '') return $(this).attr('title');
		})
		.focus(function() {
			if($(this).val() == $(this).attr('title')) $(this).val('');
		})
		.blur(function() {
			if($(this).val() === '') $(this).val($(this).attr('title'));
		})
		.closest('form').submit(function() {
			// Before submitting, remove placeholder text
			$('.placeholderInput', this).val(function() {
				var value = $(this).val(),
					placeholder_present = (value == $(this).attr('title'));

				return placeholder_present ? '' : value;
			});
		});

  $.fn.extend({
    ghostWriter: function() {
      var ghost_HTML = $('<span class="ghostwriter"><span class="ghostwriter_cache">' + $(this).val() + '</span>' + $(this).data('ghost-text') + '</span>');

      if($(this).val() === '') ghost_HTML.hide();

      $(this)
        .wrap('<span class="ghostwriter_cache_wrapper" />')
        .parent()
          .append(ghost_HTML).end()
        .bind('input paste cut keyup', function() {
          var input_text_wrapper  = $(this).parent().find('.ghostwriter'),
              input_text          = input_text_wrapper.find('.ghostwriter_cache');

          input_text.html( $(this).val() );

          if( $(this).val() === '' ) input_text_wrapper.hide();
          else input_text_wrapper.show();
        });
    }
  });

  $('.ghostwriter_input').ghostWriter();


	// Global TinyMCE editor config
	// @link: http://tinymce.moxiecode.com/wiki.php/Configuration
	$('textarea.tinymce').tinymce({
		script_url: '/javascripts/tiny_mce/tiny_mce.js',
		doctype: '<!DOCTYPE html>',
		content_css: ('/stylesheets/whitegallery/tinymce_editor.css?' + (new Date().getTime())),
		plugins: 'paste',
		paste_strip_class_attributes: 'all',
		paste_remove_spans: true,
		paste_text_sticky: true,
		theme: 'advanced',
		theme_advanced_toolbar_location: 'top',
		theme_advanced_toolbar_align: 'left',
		theme_advanced_buttons1: '\
			bold,italic,underline,strikethrough,separator,\
			justifyleft,justifycenter,justifyright,separator,\
			bullist,numlist,separator,\
			blockquote,separator,\
			link,unlink,separator,\
			pastetext,pasteword,separator,\
			undo,redo,separator,\
			code\
		',
		theme_advanced_buttons2: 'formatselect,fontsizeselect,separator,charmap',
		theme_advanced_buttons3: '',
		theme_advanced_blockformats: 'h3,h4,p',
		theme_advanced_font_sizes: 'Small=0.8em,Normal=1em,Large=1.2em',
		theme_advanced_statusbar_location: 'bottom',
		theme_advanced_resizing : true
	});

	// FIXME Are these still in use..?
	function remove_fields(link) {
    $(link).prev("input[type=hidden]").val("1");
    $(link).closest(".fields").hide();
	}

	function add_fields(link, association, content) {
    var new_id = new Date().getTime();
    var regexp = new RegExp("new_" + association, "g");
    $(link).parent().before(content.replace(regexp, new_id));
	}

	// User menu
	$.get('/personalized_fragments/user_menu');

	// Post details
	$('.postDetailsGalleryList a').bind('click', function(event) {
		event.preventDefault();

		if ($(this).parent('li').hasClass('selected'))
			return;

		var clickedElement = $(this);
		var image = clickedElement.closest('.postContent').find('.postImage');

		image.fadeTo('fast', 0.25, function(){
			$(this).attr('src', clickedElement.data('image-url'));
			$(this).closest('.postContent').find('.postDetailsGalleryList li').removeClass('selected');
			clickedElement.closest('li').addClass('selected');
		});
	});

	$('.postImage').load(function(){
		$(this).fadeTo('fast', 1.0);
	});

  $('.closeFancyBox').live('click', function(){
    $.fancybox.close();
  });
});

// Flash messages
function display_flash_message(key, message) {
  $('<p class="notification notification' + key + ' copyPrimary" style="display:none">' + message + '</p>').appendTo('#flash_messages').slideDown("slow");
}

function display_toggle_links(current_user_id, false_css_selector, true_css_selector, url) {
  if(current_user_id !== 0) {
    $(false_css_selector).each(function(index) {
      var target_user_id = $(this).data('target-id');

      $.ajax({
        url: url,
        context: document.body,
        data: 'current_user_id='+current_user_id+'&id='+target_user_id,
        type: 'POST',
        success: function(data){
          if(data == 'true') {
            $(true_css_selector).fadeIn('slow');
          } else {
            $(false_css_selector).fadeIn('slow');
          }
        }
      });
    });
  }
}

// User Manager
var UserManager = Class.extend({
	init: function() {
		this.current_user = null;
	},
	setCurrentUser: function(user) {
		this.current_user = $.parseJSON(user);
		$(this).trigger('currentUserChanged');
	},
	isLoggedIn: function() {
		return (this.current_user !== null);
	},
	id: function() {
		return this.isLoggedIn() ? this.current_user.user.id : null;
	},
	isAdmin: function() {
		return this.isLoggedIn() ? this.current_user.user.is_admin : null;
	},
	firstName: function() {
		return this.isLoggedIn() ? this.current_user.user.first_name : null;
	},
	lastName: function() {
		return this.isLoggedIn() ? this.current_user.user.last_name : null;
	},
	name: function() {
		return this.isLoggedIn() ? this.firstName() : null;
	}
});

var userManager = new UserManager();

// A support-method for the XFBML-login-buttons throughout the site.
// When clicking any of these buttons, they need to specify this method
// as the onlogin property, to complete the login.
// Example:
// <fb:login-button onlogin="finish_fb_login()">Log in</fb:login-button>
function finish_fb_login() {
	window.location = '/auth/facebook/callback';
}

