(function($) {

	ContactView = Backbone.View.extend({
		el: $('.contactWrapper')
		
		,events: {
			'click .btn_contact'				: 'clickHandler'
			,'focus .btn_contact'				: 'contactFocusHandler'
			// ,'blur a'							: 'contactBlurHandler'
			,'keydown'							: 'escapeHandler'
			,'click .button'					: 'buttonClickHandler'
		}
		
		,initialize: function initialize () {
			
			_.bindAll(this, 'render');
			this.render();
		}
		
		,render: function render () {
			var self = this,
				originalPosition;

			// Get the original position of the contact module
			// from the css and store it in this.originalPosition
			this.originalPosition = parseInt( this.el.css('right') );
			this.originalTopPosition = parseInt( this.el.css('top') );
			this.contactModule = $('.module_contact');

			pubsub.subscribe('ryerson/windowScroll', function () {
				self.reposition();
			});
		}

		,clickHandler: function clickHandler (ev) {
			ev.preventDefault();

			if ( $(ev.currentTarget).parent('section').hasClass('closed') ) {
				this.reveal();	
			} else {
				this.conceal();
			}
		}

		,contactFocusHandler: function contactFocusHandler (ev) {

			this.reveal();
		}

		,buttonClickHandler: function buttonClickHandler (ev) {
			ev.preventDefault();

			var contactModule = new ContactModule();
		}

		,contactBlurHandler: function contactBlurHandler (ev) {
			ev.preventDefault();
			// We need to compare a string attribute here to make sure
			// that the links are the same
			var currentImgSrc = $(ev.currentTarget).children('img').attr('src');
			var lastImgSrc = $('a:last', this.el).children('img').attr('src');

			if ( currentImgSrc == lastImgSrc ) {

				this.conceal();
			}
		}

		,escapeHandler: function escapeHandler (ev) {
			// If the keycode == 27 (escape key) then hide the contact module
			if ( ev.keyCode == 27 ) {
				this.conceal();
			}
		}
		
		,reveal: function reveal () {
			var wrapper = $(this.el);
			var self = this;
			
			this.contactModule.css('display', 'block');

			wrapper.removeClass('closed').stop().animate({
				right: 0
			}, 
			{
				duration: 225
				,easing: 'easeInOutQuad'
				,complete: function () {
					wrapper.addClass('open');
					wrapper.find('a:first').focus();
				}
			});
		}
		
		,conceal: function conceal () {
			var wrapper = $(this.el), 
				self = this;
			
			wrapper.removeClass('open').stop().animate({
				'right': self.originalPosition
			}, 
			{
				duration: 225
				,easing: 'easeInOutQuad'
				,complete: function () {
					wrapper.addClass('closed');
					self.contactModule.css('display', 'block');
				}
			});
		}

		,reposition: function reposition () {
			var scrollPosition = parseInt( $(window).scrollTop() );
			var newPosition = this.originalTopPosition + scrollPosition

			this.el.stop().animate({
				'top': newPosition
			}, {
				duration: 500
				,easing: 'jswing'
			});
		}
	});

}(jQuery));
