/**
 * Unobtrusive scripting adapter for jQuery
 *
 * Requires jQuery 1.4.3 or later.
 * https://github.com/rails/jquery-ujs
 */

(function($) {
	// Triggers an event on an element and returns the event result
	function fire(obj, name, data) {
		var event = new $.Event(name);
		obj.trigger(event, data);
		return event.result !== false;
	}

	// Submits "remote" forms and links with ajax
	function handleRemote(element) {
		var method, url, data,
			dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);

		if (element.is('form')) {
			method = element.attr('method');
			url = element.attr('action');
			data = element.serializeArray();
			// memoized value from clicked submit button
			var button = element.data('ujs:submit-button');
			if (button) {
				data.push(button);
				element.data('ujs:submit-button', null);
			}
		} else {
			method = element.attr('data-method');
			url = element.attr('href');
			data = null;
		}

		$.ajax({
			url: url, type: method || 'GET', data: data, dataType: dataType,
			// stopping the "ajax:beforeSend" event will cancel the ajax request
			beforeSend: function(xhr, settings) {
				if (settings.dataType === undefined) {
					xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
				}
				return fire(element, 'ajax:beforeSend', [xhr, settings]);
			},
			success: function(data, status, xhr) {
				element.trigger('ajax:success', [data, status, xhr]);
			},
			complete: function(xhr, status) {
				element.trigger('ajax:complete', [xhr, status]);
			},
			error: function(xhr, status, error) {
				element.trigger('ajax:error', [xhr, status, error]);
			}
		});
	}

	// Handles "data-method" on links such as:
	// <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
	function handleMethod(link) {
		var href = link.attr('href'),
			method = link.attr('data-method'),
			csrf_token = $('meta[name=csrf-token]').attr('content'),
			csrf_param = $('meta[name=csrf-param]').attr('content'),
			form = $('<form method="post" action="' + href + '"></form>'),
			metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';

		if (csrf_param !== undefined && csrf_token !== undefined) {
			metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
		}

		form.hide().append(metadata_input).appendTo('body');
		form.submit();
	}

	function disableFormElements(form) {
		form.find('input[data-disable-with]').each(function() {
			var input = $(this);
			input.data('ujs:enable-with', input.val())
				.val(input.attr('data-disable-with'))
				.attr('disabled', 'disabled');
		});
	}

	function enableFormElements(form) {
		form.find('input[data-disable-with]').each(function() {
			var input = $(this);
			input.val(input.data('ujs:enable-with')).removeAttr('disabled');
		});
	}

	function allowAction(element) {
		var message = element.attr('data-confirm');
		return !message || (fire(element, 'confirm') && confirm(message));
	}

	$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
		var link = $(this);
		if (!allowAction(link)) return false;

		if (link.attr('data-remote')) {
			handleRemote(link);
			return false;
		} else if (link.attr('data-method')) {
			handleMethod(link);
			return false;
		}
	});

	$('form').live('submit.rails', function(e) {
		var form = $(this);
		if (!allowAction(form)) return false;

		if (form.attr('data-remote')) {
			handleRemote(form);
			return false;
		} else {
			disableFormElements(form);
		}
	});

	$('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() {
		var button = $(this);
		if (!allowAction(button)) return false;
		// register the pressed submit button
		var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null;
		button.closest('form').data('ujs:submit-button', data);
	});

	$('form').live('ajax:beforeSend.rails', function(event) {
		if (this == event.target) disableFormElements($(this));
	});

	$('form').live('ajax:complete.rails', function(event) {
		if (this == event.target) enableFormElements($(this));
	});
})( jQuery );(function($) {

	$.fn.submitWith = function(options) {

		var defaults = {
			disableText: 'Submitting...',
			disableClass: 'disabled-submit-activity',
			delay: 3000
		}

		var settings = $.extend({}, defaults, options);

		return this.each(function() {

			var $this = $(this);
			$this.attr('data-enableText', $this.attr('value'));

			$this.enable = function() {
				var $this = $(this);
				$this.removeAttr('disabled');
				$this.attr('value', $this.attr('data-enableText'));
				$("." + settings.disableClass).remove();
				$this.show();
			}
			
			$this.bind("click", function() { 

				if (typeof(do_not_submit) != 'undefined' && do_not_submit == true) {
					return;
				} else {
					$this.attr('value', settings.disableText);
					$this.attr("disabled", "true");
					$this.hide();
					$this.after('<span class="' + settings.disableClass + '"><img src="/spitfire/images/progress/activity.gif" class="activity-indicator" /> ' + settings.disableText + '</span>');
					$this.parents("form:first").trigger("submit");	
					/* setTimeout(function() { $this.enable(); }, settings.delay); */
				}

			});

		});
	}

})(jQuery);/*
 * Facebox (for jQuery)
 * version: 1.3
 * @requires jQuery v1.2 or later
 * @homepage https://github.com/defunkt/facebox
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright Forever Chris Wanstrath, Kyle Neath
 *
 * Usage:
 *
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox()
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    jQuery.facebox('some html')
 *    jQuery.facebox('some html', 'my-groovy-style')
 *
 *  The above will open a facebox with "some html" as the content.
 *
 *    jQuery.facebox(function($) {
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page, an image, or the contents of a div:
 *
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
 *    jQuery.facebox({ image: 'stairs.jpg' })
 *    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
 *    jQuery.facebox({ div: '#box' })
 *    jQuery.facebox({ div: '#box' }, 'my-groovy-style')
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *    afterClose.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading(data.settings || [])

    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <div class="content"> \
        </div> \
        <a href="#" class="close"></a> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').show().css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	$(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2)
      })

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').empty().append(data)
      $('#facebox .popup').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return

    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.bind('click.facebox', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\\.(' + imageTypes + ')(\\?.*)?$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close')
      .click($.facebox.close)
      .append('<img src="'
              + $.facebox.settings.closeImage
              + '" class="close_image" title="close">')
  }

  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.facebox.jqxhr = $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#facebox_overlay').length == 0)
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide")
      $("#facebox_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    if ($.facebox.jqxhr) {
      $.facebox.jqxhr.abort()
      $.facebox.jqxhr = null
    }
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      $('#facebox .loading').remove()
      $(document).trigger('afterClose.facebox')
    })
    hideOverlay()
  })

})(jQuery);
var flash = {
	
	message: function(message_type, message, options) {
		if (!(typeof message === "undefined")) {
			jQuery('#flash-message').html(message);
			jQuery('#flash-message-container').removeClass('flash-info flash-success flash-error').addClass('flash-' + message_type);
			jQuery('#flash-message-container').messages(options);		
		}
	},

	fetch: function() {
		
		if (typeof flash.panel === 'undefined') {
			flash.panel = jQuery('body').append('<div id="flash-message-container"><div id="flash-message" class="flash-message">&nbsp;</div><a href="#" id="flash-close" onclick="$(this).parent().hide();return false;">(close this message)</a></div>');			
		}
		
		jQuery.ajaxSetup({ cache: false });
		jQuery.getJSON('/**/messages.json', {}, function(data) {
			if (data.has_messages == true) {
				flash.message('success', data.success, { timer: 5 });
				flash.message('info', data.info, { timer: 10 });
				flash.message('error', data.error, { timer: 50 });
			}			
		});
	}

}

jQuery.fn.extend({ 

	messages: function(options) {

		var defaults = {
			animationIn: 'slide',
			animationOut: 'slide',
			easingIn: 'easeOutBounce',
			easingOut: 'easeOutBounce',
			animationSpeed: 'normal',
			delay: 0,
			timer: null
		};
				
		var settings = jQuery.extend(defaults, options);
	
		settings.delay = settings.delay * 1000;

		if (settings.timer != null) {
			settings.timer = settings.timer * 1000;
		}
		
		return this.each(function() {
				
			var element = jQuery(this);

			jQuery(element).wrap('<div id="messages-container"></div>');
	
			jQuery('#messages-container').css({'position':'fixed', 'z-index':'10000', 'top':'0', 'left':'0', 'width':'100%' });

			switch (settings.animationIn) {
				case "slide":
					jQuery('#messages-container > *').hide().delay(settings.delay).animate({ height: 'show' }, settings.animationSpeed, settings.easingIn);
					break;
				case "fade":
					jQuery('#messages-container > *').hide().delay(settings.delay).animate({ opacity: "show" }, settings.animationSpeed, settings.easingIn);
					break;
				case "none":
					jQuery('#messages-container > *').hide().delay(settings.delay).show(0);
					break;
				default:
					alert('The animationIn option only accepts "slide", "fade", or "none"');
			}
				
			switch (settings.animationOut) {

				case "slide":

					if (settings.timer != null) {
						jQuery('#messages-container > *').delay(settings.timer).animate({ height: 'hide' }, settings.animationSpeed, settings.easingOut);
					}
						
					jQuery(settings.hide).click(function() {
						jQuery('#messages-container > *').stop().animate({ height: 'hide' }, settings.animationSpeed, settings.easingOut);	
					});
					
					break;
					
				case "fade":
					
					if (settings.timer != null) {
						jQuery('#messages-container > *').delay(settings.timer).animate({ opacity: 'hide' }, settings.animationSpeed, settings.easingOut);
					}

					jQuery(settings.hide).click(function() {
						jQuery('#messages-container > *').stop().animate({ opacity: 'hide' }, settings.animationSpeed, settings.easingOut);
					});

					break;
					
				case "none":
					
					if (settings.timer != null){
						jQuery('#messages-container > *').delay(settings.timer).hide(0);
					}
					
					jQuery(settings.hide).click(function() {
						jQuery('#messages-container > *').hide();
					});
					
					break;
					
				default:
					alert('animationOut can only be "slide", "fade" or "none"');
			}
	
		});
	}
});// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license

(function($) {
    
    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        this.fixTitle();
    }
    
    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();
                
                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
                
                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });
                
                var actualWidth = $tip[0].offsetWidth, actualHeight = $tip[0].offsetHeight;
                var gravity = (typeof this.options.gravity == 'function')
                                ? this.options.gravity.call(this.$element[0])
                                : this.options.gravity;
                
                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }
                
                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }
                
                $tip.css(tp).addClass('tipsy-' + gravity);
                
                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },
        
        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },
        
        fixTitle: function() {
            var $e = this.$element;
            if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
                $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
            }
        },
        
        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            this.fixTitle();
            var title, o = this.options;
            if (typeof o.title == 'string') {
                title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },
        
        tip: function() {
            if (!this.$tip) {
                this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
            }
            return this.$tip;
        },
        
        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },
        
        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };
    
    $.fn.tipsy = function(options) {
        
        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            var tipsy = this.data('tipsy');
            if (tipsy) tipsy[options]();
            return this;
        }
        
        options = $.extend({}, $.fn.tipsy.defaults, options);
        
        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }
        
        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                tipsy.fixTitle();
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };
        
        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };
        
        if (!options.live) this.each(function() { get(this); });
        
        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }
        
        return this;
        
    };
    
    $.fn.tipsy.defaults = {
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };
    
    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };
    
})(jQuery);
(function($) {

	$.fn.prioritise = function(options) {

		var defaults = {
			remote_url: '',
			list_items: '.list'
		}

		var settings = $.extend({}, defaults, options);

		return this.each(function() {
			var $this = $(this);

			$this.sortable({
				// axis: 'y', 
				dropOnEmpty: false, 
				handle: '.handle', 
				cursor: 'crosshair',
				items: settings.list_items,
				opacity: 0.4,
				scroll: true,
				update: function() {
					$.ajax({
						type: 'post',
						dataType: 'script',
						url: settings.remote_url,
						data: { 
							'_method': 'post',
							'authenticity_token': rails_authenticity_token,
							'order': $this.sortable('serialize', { key: 'item', expression: (/(.+)/) })
						},
						complete: function(request) {
							$this.effect('highlight');
						}
					});					
				}	
			});
		});
	}

})(jQuery);/**
* Inline Confirmation plugin for jQuery
*
* One of the less obtrusive ways of implementing a confirmation dialogue. Requires jQuery 1.4.2+.
*
* v1.4.1
*
* Copyright (c) 2010 Fred Wu
*
* Released under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

/**
* Usage:
*
* // using default options
* $("a.delete").inlineConfirmation();
*
* // using some custom options
* $("a.delete").inlineConfirmation({
* confirm: "<a href='#' class='confirm-yes'>Yes</a>",
* cancel: "<a href='#' class='confirm-no'>No</a>",
* separator: " | ",
* reverse: true,
* bindsOnEvent: "hover",
* confirmCallback: function(action) {
* action.parent().fadeIn();
* }
* });
*
* Configuration options:
*
* confirm string the HTML for the confirm action (default: "<a href='#'>Confirm</a>")
* cancel string the HTML for the cancel action (default: "<a href='#'>Cancel</a>")
* separator string the HTML for the separator between the confirm and the cancel actions (default: " ")
* reverse boolean revert the confirm and the cancel actions (default: false)
* hideOriginalAction boolean whether or not to hide the original action, useful for display the dialogue as a modal if set to false (default: true)
* bindsOnEvent string the JavaScript event handler for binding the confirmation action (default: "click")
* expiresIn integer seconds before the confirmation dialogue closes automatically, 0 to disable this feature (default: 0)
* confirmCallback function the callback function to execute after the confirm action, accepts the original action object as an argument
* cancelCallback function the callback function to execute after the cancel action, accepts the original action object as an argument
*/

(function($){

  $.fn.inlineConfirmation = function(options) {
    var defaults = {
      confirm: "<a href='#'>Confirm</a>",
      cancel: "<a href='#'>Cancel</a>",
      separator: " ",
      reverse: false,
      hideOriginalAction: true,
      bindsOnEvent: "click",
      expiresIn: 0,
      confirmCallback: function() { return true; },
      cancelCallback: function() { return true; }
    };

    var original_action;
    var timeout_id;
    var all_actions = $(this);
    var options = $.extend(defaults, options);
    var block_class = "inline-confirmation-block";
    var confirm_class = "inline-confirmation-confirm";
    var cancel_class = "inline-confirmation-cancel";
    var action_class = "inline-confirmation-action";

    options.confirm = "<span class='" + action_class + " " + confirm_class + "'>" + options.confirm + "</span>";
    options.cancel = "<span class='" + action_class + " " + cancel_class + "'>" + options.cancel + "</span>";

    var action_set = options.reverse === false
      ? options.confirm + options.separator + options.cancel
      : options.cancel + options.separator + options.confirm;

    $(this).live(options.bindsOnEvent, function(e) {
      original_action = $(this);

      all_actions.show();
      $("span." + block_class).hide();

      if (options.hideOriginalAction === true) {
        $(this).trigger("update").hide();
      }

      var active_action_set = $("span." + block_class, $(this).parent());

      if (active_action_set.length > 0) {
        active_action_set.show();
      } else {
        $(this).after("<span class='" + block_class + "'>" + action_set + "</span>");
      }

      if (options.expiresIn > 0) {
        timeout_id = setTimeout(function() {
          $("span." + block_class, original_action.parent()).hide();
          original_action.show();
        }, options.expiresIn * 1000);
      }

      e.preventDefault();
    });

/*
    $(this).parent().delegate("span." + action_class, "click", function() {
      clearTimeout(timeout_id);
      $(this).parent().hide();
      original_action.show();

      var args = new Array();
      args[0] = original_action;

      if ($(this).hasClass(confirm_class)) {
        options.confirmCallback.apply(this, args);
      } else {
        options.cancelCallback.apply(this, args);
      }
      return false;
    });
*/
  };

})(jQuery);function setup_facebox($) {
	$('#facebox .tooltip').tipsy();
	$('#facebox #save_button').submitWith({ disableText : 'Saving...' });	
	$('#facebox .content a[rel*=facebox]').facebox({}); 
	$('#facebox form').submit(function() {
		$.post(this.action, $(this).serialize(), function(data) { 
			flash.fetch();
			$('#facebox .facebox-content').html(data); setup_facebox($);  
		}, "script");		
		return false;  
	});
}

jQuery(document).ready(function($) {

	$('a[rel*=facebox]').facebox({ 
		opacity: false, 
		loadingImage: '/spitfire/facebox/loading.gif', 
		closeImage: '/spitfire/facebox/close-button.png' 
	});

	$(document).bind('reveal.facebox', function() { setup_facebox($); });
	
	$('a.confirm-destroy').live('click', function() {
		
		action = $(this).closest('span.trash').find('.destroy');
		id = action.attr('id').replace('destroy_', '');
		href = action.attr('href');

		jQuery.ajax({
			url: href,
			type: 'post',
			dataType: 'script',
			data: { 
				'_method': 'delete',
				'authenticity_token': rails_authenticity_token, 
				'id': id
			},
			success: function(data, textStatus) {
				jQuery('#' + id).fadeOut('normal', function() {
					$(this).remove();
					flash.message('success', '#' + id + ' successfully removed');
				});
			},
			error: function (request, textStatus, errorThrown) {
				var message = 'Sorry, but there was an error processing your request.';
				if (request.status == 403) { message = request.responseText; }					
				flash.message('error', message);										
				$('.mark-destroy').removeClass('mark-destroy');					
				obj;
			}
		});	
	
		return false;
	});

	$('a.destroy').inlineConfirmation({	
		confirm: '<a href="#" class="confirm-destroy">Yes, Destroy</a>',
		cancel: '<a href="#" class="confirm-cancel">Cancel</a>',
		expiresIn: 0,
		hideOriginalAction: true
	});
	
	$('a.confirm-cancel').live('click', function() {
		$('.mark-destroy').removeClass('mark-destroy');
		confirm_container = $(this).closest('span.inline-confirmation-block');
		confirm_container.hide();
		$('.destroy').show();
		confirm_container.remove();
		return false;
	});	
    
	$('a.destroy').live('click', function() {
		$('.mark-destroy').removeClass('mark-destroy');
		$(this).closest('div').addClass('mark-destroy');
	});

	$('a.tooltip').tipsy({ live: true, gravity: 'nw', delayIn: 100, delayOut: 1000, live: true, fade: true });
		
	$('a.clipboard').zclip({
		path:'/spitfire/zclip/ZeroClipboard.swf',
        copy:function() { return $(this).attr('data-text'); },
        afterCopy:function() { $(this).tipsy("hide"); }
	});

	flash.fetch();

});$(document).ready(function() {

	var spitfire = {
		hover_focus: function(obj) { 
			if (!obj.attr("data-opacity")) {
				obj.attr("data-opacity", obj.css("opacity"));				
			}			
			obj.stop().animate({ "opacity": 1 }, "slow"); 
		},
		hover_unfocus: function(obj) { obj.stop().animate({ "opacity": obj.attr("data-opacity") }, "slow"); }
	};

	$(".sb").live({
		mouseenter: function() {
			spitfire.hover_focus($(this));
		},
		mouseleave: function() {
			spitfire.hover_unfocus($(this));
		}
	});

	$(".list").live({
		mouseenter: function() {
			$(this).find('a.sb').each(function() { spitfire.hover_focus($(this), 0.4); });
		},
		mouseleave: function() {
			$(this).find('a.sb').each(function() { spitfire.hover_unfocus($(this)); });
		}
	});
});/*
 * zClip :: jQuery ZeroClipboard v1.1.1
 * http://steamdev.com/zclip
 *
 * Copyright 2011, SteamDev
 * Released under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Date: Wed Jun 01, 2011
 */

(function(a){a.fn.zclip=function(c){if(typeof c=="object"&&!c.length){var b=a.extend({path:"ZeroClipboard.swf",copy:null,beforeCopy:null,afterCopy:null,clickAfter:true,setHandCursor:true,setCSSEffects:true},c);return this.each(function(){var e=a(this);if(e.is(":visible")&&(typeof b.copy=="string"||a.isFunction(b.copy))){ZeroClipboard.setMoviePath(b.path);var d=new ZeroClipboard.Client();if(a.isFunction(b.copy)){e.bind("zClip_copy",b.copy)}if(a.isFunction(b.beforeCopy)){e.bind("zClip_beforeCopy",b.beforeCopy)}if(a.isFunction(b.afterCopy)){e.bind("zClip_afterCopy",b.afterCopy)}d.setHandCursor(b.setHandCursor);d.setCSSEffects(b.setCSSEffects);d.addEventListener("mouseOver",function(f){e.trigger("mouseenter")});d.addEventListener("mouseOut",function(f){e.trigger("mouseleave")});d.addEventListener("mouseDown",function(f){e.trigger("mousedown");if(!a.isFunction(b.copy)){d.setText(b.copy)}else{d.setText(e.triggerHandler("zClip_copy"))}if(a.isFunction(b.beforeCopy)){e.trigger("zClip_beforeCopy")}});d.addEventListener("complete",function(f,g){if(a.isFunction(b.afterCopy)){e.trigger("zClip_afterCopy")}else{if(g.length>500){g=g.substr(0,500)+"...\n\n("+(g.length-500)+" characters not shown)"}e.removeClass("hover");alert("Copied text to clipboard:\n\n "+g)}if(b.clickAfter){e.trigger("click")}});d.glue(e[0],e.parent()[0]);a(window).bind("load resize",function(){d.reposition()})}})}else{if(typeof c=="string"){return this.each(function(){var f=a(this);c=c.toLowerCase();var e=f.data("zclipId");var d=a("#"+e+".zclip");if(c=="remove"){d.remove();f.removeClass("active hover")}else{if(c=="hide"){d.hide();f.removeClass("active hover")}else{if(c=="show"){d.show()}}}})}}}})(jQuery);var ZeroClipboard={version:"1.0.7",clients:{},moviePath:"ZeroClipboard.swf",nextId:1,$:function(a){if(typeof(a)=="string"){a=document.getElementById(a)}if(!a.addClass){a.hide=function(){this.style.display="none"};a.show=function(){this.style.display=""};a.addClass=function(b){this.removeClass(b);this.className+=" "+b};a.removeClass=function(d){var e=this.className.split(/\s+/);var b=-1;for(var c=0;c<e.length;c++){if(e[c]==d){b=c;c=e.length}}if(b>-1){e.splice(b,1);this.className=e.join(" ")}return this};a.hasClass=function(b){return !!this.className.match(new RegExp("\\s*"+b+"\\s*"))}}return a},setMoviePath:function(a){this.moviePath=a},dispatch:function(d,b,c){var a=this.clients[d];if(a){a.receiveEvent(b,c)}},register:function(b,a){this.clients[b]=a},getDOMObjectPosition:function(c,a){var b={left:0,top:0,width:c.width?c.width:c.offsetWidth,height:c.height?c.height:c.offsetHeight};if(c&&(c!=a)){b.left+=c.offsetLeft;b.top+=c.offsetTop}return b},Client:function(a){this.handlers={};this.id=ZeroClipboard.nextId++;this.movieId="ZeroClipboardMovie_"+this.id;ZeroClipboard.register(this.id,this);if(a){this.glue(a)}}};ZeroClipboard.Client.prototype={id:0,ready:false,movie:null,clipText:"",handCursorEnabled:true,cssEffects:true,handlers:null,glue:function(d,b,e){this.domElement=ZeroClipboard.$(d);var f=99;if(this.domElement.style.zIndex){f=parseInt(this.domElement.style.zIndex,10)+1}if(typeof(b)=="string"){b=ZeroClipboard.$(b)}else{if(typeof(b)=="undefined"){b=document.getElementsByTagName("body")[0]}}var c=ZeroClipboard.getDOMObjectPosition(this.domElement,b);this.div=document.createElement("div");this.div.className="zclip";this.div.id="zclip-"+this.movieId;$(this.domElement).data("zclipId","zclip-"+this.movieId);var a=this.div.style;a.position="absolute";a.left=""+c.left+"px";a.top=""+c.top+"px";a.width=""+c.width+"px";a.height=""+c.height+"px";a.zIndex=f;if(typeof(e)=="object"){for(addedStyle in e){a[addedStyle]=e[addedStyle]}}b.appendChild(this.div);this.div.innerHTML=this.getHTML(c.width,c.height)},getHTML:function(d,a){var c="";var b="id="+this.id+"&width="+d+"&height="+a;if(navigator.userAgent.match(/MSIE/)){var e=location.href.match(/^https/i)?"https://":"http://";c+='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+e+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+d+'" height="'+a+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+b+'"/><param name="wmode" value="transparent"/></object>'}else{c+='<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+d+'" height="'+a+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+b+'" wmode="transparent" />'}return c},hide:function(){if(this.div){this.div.style.left="-2000px"}},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML="";var a=document.getElementsByTagName("body")[0];try{a.removeChild(this.div)}catch(b){}this.domElement=null;this.div=null}},reposition:function(c){if(c){this.domElement=ZeroClipboard.$(c);if(!this.domElement){this.hide()}}if(this.domElement&&this.div){var b=ZeroClipboard.getDOMObjectPosition(this.domElement);var a=this.div.style;a.left=""+b.left+"px";a.top=""+b.top+"px"}},setText:function(a){this.clipText=a;if(this.ready){this.movie.setText(a)}},addEventListener:function(a,b){a=a.toString().toLowerCase().replace(/^on/,"");if(!this.handlers[a]){this.handlers[a]=[]}this.handlers[a].push(b)},setHandCursor:function(a){this.handCursorEnabled=a;if(this.ready){this.movie.setHandCursor(a)}},setCSSEffects:function(a){this.cssEffects=!!a},receiveEvent:function(d,f){d=d.toString().toLowerCase().replace(/^on/,"");switch(d){case"load":this.movie=document.getElementById(this.movieId);if(!this.movie){var c=this;setTimeout(function(){c.receiveEvent("load",null)},1);return}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var c=this;setTimeout(function(){c.receiveEvent("load",null)},100);this.ready=true;return}this.ready=true;try{this.movie.setText(this.clipText)}catch(h){}try{this.movie.setHandCursor(this.handCursorEnabled)}catch(h){}break;case"mouseover":if(this.domElement&&this.cssEffects){this.domElement.addClass("hover");if(this.recoverActive){this.domElement.addClass("active")}}break;case"mouseout":if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass("active")){this.domElement.removeClass("active");this.recoverActive=true}this.domElement.removeClass("hover")}break;case"mousedown":if(this.domElement&&this.cssEffects){this.domElement.addClass("active")}break;case"mouseup":if(this.domElement&&this.cssEffects){this.domElement.removeClass("active");this.recoverActive=false}break}if(this.handlers[d]){for(var b=0,a=this.handlers[d].length;b<a;b++){var g=this.handlers[d][b];if(typeof(g)=="function"){g(this,f)}else{if((typeof(g)=="object")&&(g.length==2)){g[0][g[1]](this,f)}else{if(typeof(g)=="string"){window[g](this,f)}}}}}}};
