/**
 * @author		Konstantin Vyalukhin <kst404@gmail.com>
 */

function gcMessageBox( message, e ) {
	if( e instanceof Event ) {
		positionCss = {
			'left': (e.pageX + 322 > $( window ).width() ? $( window ).width() - 322 : e.pageX ),
			'top': e.pageY+10
		};
	}
	else {
		positionCss = {
			'left': e.left ? e.left : $( window ).width()/2 - 161,
			'top': e.top ? e.top : $( window ).height()/2 - 150
		};
	}
	var messageBox = $('<div class="message-box">'+message+'</div>')
	.css( positionCss )
	.click(function( event ){
		event.stopPropagation();
	})
	.appendTo( document.body );
	
	$(document)
		.one('click', function( event ){
			$( messageBox ).remove();
		});
}

function gcReplaceTargetHtml( e, val ) {
	$( e.currentTarget ).html( val );
}

function gcMessageBoxNeedToSignIn( e ){
	gcMessageBox( 'Please <b>Log in</b><div><form method="post" action="/signin.do" class="form-horisontal"><input type="hidden" name="here" value="1"/><div class="clearfix form-row"><div class="form-label"><label for="userName">E-mail</label></div><div class="form-field"><input type="text" name="userName" id="userName" maxlength="255" style="width: 14em;" /></div></div><div class="clearfix form-row"><div class="form-label"><label for="password">Password</label></div><div class="form-field"><input type="password" name="password" id="password" maxlength="16" style="width: 14em;" /></div></div><div class="form-button"><input type="submit" class="button-submit" value="Log in &gt;&gt;" /></div></form></div> or <a href="/register">Register</a>', e );
	$('#userName').focus();
}

function gcInit(){
	$(function(){
		$('a[rel="external"]').attr('target', '_blank');
	});
}

function gcAjaxifyLink( jqSelector, confirmFuction ){
		var confirm = confirmFuction;
		$( jqSelector ).click(function( event ){
			event.preventDefault();
			var confirmResult = true;
			var t = this;
			var e = event;
			if( 'function' == typeof( confirm ) )
				confirmResult = confirm( event );

			if( confirmResult )				
				$.getJSON(
					this.href,
					function( data ){
						switch( data.errorCode ) {
							case 200:
								if( 'undefined' != data.callback ) {
									eval('var callback = ' + data.callback);
									callback( e );
								}
								else
									gcReplaceTargetHtml( e, data.title );
								break;
							case 401:
								gcMessageBoxNeedToSignIn( e );
								break;
							default:
								gcMessageBox( data.errorMessage, e );
						}
					}
				);
		});
}

function gcAjaxIamInterested() {
	$(function(){
		gcAjaxifyLink( '.agenda-event-iaminterested' );
	});
}

function gcAjaxAddToCalendar() {
	$(function(){
		gcAjaxifyLink( '.agenda-event-iamgoing' );
	});
}

function GcSliderHorisontal( options ){
	this.options = options;
	this.init();
}

GcSliderHorisontal.prototype = {
	defaults: {
		applyTo: '',
		event: 'hover',
		speed: 'normal',
		delay: 200,
		bodyWidth: 0,
		selected: 'selected'
	},
	isRunning: false,
	activeTimeout: null,
	options: {},
	currentItem: null,
	
	init: function(){
		for( var i in this.defaults ) {
			if( undefined == this.options[ i ] )
				this.options[ i ] = this.defaults[ i ];
		}
		
		$( this.options.applyTo )
			.removeClass( 'slider-item-hover' )
			.filter(':last')
				.addClass( this.options.selected )
			.end()
			.each( function( i ){
				var position = $( this ).position();
				$( this )
					.css({
						left: position.left
					});
			})
			.css({
				width: 396,
				overflow: 'hidden',
				position: 'absolute'
			});
			
		this.setEventHandlers();
		
		this.currentItem = $( this.options.applyTo ).filter(':last');
	},
	
	setEventHandlers: function(){
		var t = this;
		
		switch( this.options.event ) {
			case 'hover':
				$( this.options.applyTo )
					.bind( 'mouseenter', function( e ){
						t.activeTimeout = setTimeout( function(){
							t.hoverHandler( e );
						}, t.options.delay );
					})
					.bind( 'mousemove', function( e ){
						t.moveHandler( e );
					})
					.bind( 'mouseleave', function( e ){
						if( t.activeTimeout ){
							clearTimeout( t.activeTimeout );
							t.activeTimeout = null;
						}
					});
				break;
		}
	},

	hoverHandler: function( e ) {
		if( this.isRunning )
			return;
		
		var t = this;

		if( !$( e.currentTarget ).hasClass( this.options.selected ) ) {
			this.currentItem.removeClass( this.options.selected );
			this.currentItem = $( e.currentTarget );
			this.isRunning = true;

			$( e.currentTarget )
				.addClass( this.options.selected )
				.prevAll()
				.animate( { marginLeft: '0' }, this.options.speed )
				.end()
				.animate( { marginLeft: '0' }, this.options.speed, function(){ t.isRunning = false;  } )
				.nextAll()
				.animate( { marginLeft: this.options.bodyWidth + 'px' }, this.options.speed );
/*
			$( e.currentTarget )
				.addClass( this.options.selected )
				.prevAll()
				.animate( { marginLeft: '0' }, this.options.speed )
				.end()
				.animate( { marginLeft: '0' }, this.options.speed, function(){ t.isRunning = false;  } )
				.nextAll()
				.animate( { marginLeft: this.options.bodyWidth + 'px' }, this.options.speed );
 */
		}
	},
	
	moveHandler: function( e ) {
//		var position = $( this ).offset();
//		var delta = e.pageX - position.left;
//		if( 0 < delta && 10 > delta ) {
//			$( this ).animate( { marginLeft: '+=1' }, 'normal' );
//		}
	}
}

function GcSliderVertical( options ){
	this.options = options;
	this.init();
}

GcSliderVertical.prototype = {
	defaults: {
		applyTo: '',
		header: '',
		body: '',
		event: 'hover',
		speed: 'normal',
		selected: 'selected',
		delay: 100
	},
	isRunning: false,
	activeTimeout: null,
	options: {},
	
	init: function(){
		for( var i in this.defaults ) {
			if( undefined == this.options[ i ] )
				this.options[ i ] = this.defaults[ i ];
		}
		
		this.setEventHandlers();
	},
	
	setEventHandlers: function(){
		var t = this;
		
		switch( this.options.event ) {
			case 'hover':
				$( this.options.applyTo )
					.bind( 'mouseenter', function( e ){
						t.activeTimeout = setTimeout( function(){
							t.hoverHandler( e );
						}, t.options.delay );
					})
					.bind( 'mouseleave', function( e ){
						if( t.activeTimeout ){
							clearTimeout( t.activeTimeout );
							t.activeTimeout = null;
						}
					});
				break;
		}
	},

	hoverHandler: function( e ) {
		if( this.isRunning )
			return;
		
		var t = this;
		
		this.isRunning = true;
		$( e.currentTarget )
			.children( this.options.body ).slideDown( this.options.speed, function(){ t.isRunning = false }).end()
			.children( this.options.header ).addClass( this.options.selected ).end()
			.siblings()
				.children( this.options.body ).slideUp( this.options.speed ).end()
				.children( this.options.header ).removeClass( this.options.selected );
	}
}

function GcScrollerVertical( options ){
	this.options = options;
	
	this.init();
	
	$(this.options.applyTo).filter(":first").show();
}

GcScrollerVertical.prototype = {
	defaults: {
		applyTo: '',
		body: '',
		arrowUpClass: 'arrow-up',
		arrowUpHtml: '',
		arrowUpDisabledClass: 'arrow-up-disabled',
		arrowDownClass: 'arrow-down',
		arrowDownHtml: '',
		arrowDownDisabledClass: 'arrow-down-disabled',
		bodyHeight: 0,
		speed: 'normal',
		step: '10px'
	},
	options: {},	

	init: function(){
		for( var i in this.defaults ) {
			if( undefined == this.options[ i ] )
				this.options[ i ] = this.defaults[ i ];
		}
		
		if ($(this.options.body).outerHeight() > parseInt( this.options.bodyHeight ) ) {
			this.arrowsAndHeight();
			this.setEventHandlers();
		}
	},
	
	arrowsAndHeight: function(){
		$( this.options.applyTo )
			.find( this.options.body )
				.before('<div class="' + this.options.arrowUpClass + ' '+ this.options.arrowUpDisabledClass +'">' + this.options.arrowUpHtml + '</div>')
				.after('<div class="' + this.options.arrowDownClass + '">' + this.options.arrowDownHtml + '</div>')
				.height( this.options.bodyHeight )
				.each(function( i, item ){
					var lastItem = $( item ).children(':last');
					var position = lastItem.position();
					$( item ).attr( 'listHeight', position.top + lastItem.outerHeight( true ) );
				})
			.end()
			.filter(':not(:first)')
				.css( 'display', 'none');
	},
	
	setEventHandlers: function(){
		var t = this;
		$( this.options.applyTo )
			.find( 'div.' + this.options.arrowUpClass )
				.click(function( e ){
					var movingItem = $( e.currentTarget ).next().find( 'li:first' );

					if( parseInt(movingItem.css('margin-top')) < 0 )
						movingItem.animate({marginTop: '+=' + t.options.step}, t.options.speed, function(){
							t.setArrowsDisabled( $( e.currentTarget ).next() );
						})
				})
			.end()
			.find( 'div.' + this.options.arrowDownClass )
				.click(function( e ){
					var movingItem = $( e.currentTarget ).prev().find( 'li:first' );

					var firstItemPosition = movingItem.position();
					var lastItemPosition = $( e.currentTarget ).prev().find( 'li:last' ).position();
					var lastItemBottomY = lastItemPosition.top + $( e.currentTarget ).prev().find( 'li:last' ).outerHeight(true);
					
					if( $( e.currentTarget ).prev().height() < lastItemBottomY - firstItemPosition.top ){
						movingItem.animate({marginTop: '-=' + t.options.step}, t.options.speed, function(){
							t.setArrowsDisabled( $( e.currentTarget ).prev() );
						});
					}
				});
	},
	
	setArrowsDisabled: function( currentItem ){
		var firstItemPosition = currentItem.find( 'li:first' ).position();
		var firstItemMarginTop = parseInt(currentItem.find( 'li:first' ).css('margin-top'));
		var lastItemPosition = currentItem.find( 'li:last' ).position();
		var lastItemBottomY = lastItemPosition.top + currentItem.find( 'li:last' ).outerHeight(true);
		
		if( 0 <= firstItemMarginTop )
			currentItem.prev().addClass( this.options.arrowUpDisabledClass );
		else
			currentItem.prev().removeClass( this.options.arrowUpDisabledClass );

		if( currentItem.height() >= lastItemBottomY - firstItemPosition.top )
			currentItem.next().addClass( this.options.arrowDownDisabledClass );
		else
			currentItem.next().removeClass( this.options.arrowDownDisabledClass );
	}
}


function GcCardfileHorisontal( options ){
	this.options = options;
	this.init();
}

GcCardfileHorisontal.prototype = {
	defaults: {
		applyTo: '',
		event: 'click',
		speed: 'normal',
		delay: 200,
		bodyWidth: 0,
		selected: 'selected'
	},
	isRunning: false,
	activeTimeout: null,
	options: {},
	currentItem: null,
	itemIdRegexp: null,
	pointerParentPosition: 0,
	
	init: function(){
		for( var i in this.defaults ) {
			if( undefined == this.options[ i ] )
				this.options[ i ] = this.defaults[ i ];
		}
			
		this.setEventHandlers();
		
		this.currentItem = $( this.options.applyTo ).filter(':first');
		this.itemIdRegexp = new RegExp( this.options.headerIdPrefix );
		this.pointerParentPosition = $( this.options.pointer ).parent().offset();
		
		$( '#' + this.getCardId( $( this.options.applyTo ).filter( ':first' ) ) ).css( { left: '0' } );
	},
	
	setEventHandlers: function(){
		var t = this;
		
		switch( this.options.event ) {
			case 'click':
				$( this.options.applyTo )
					.bind( 'click', function( e ){
						e.preventDefault();
						t.activeTimeout = setTimeout( function(){
							t.clickHandler( e );
						}, t.options.delay );
					});
				break;
		}
	},

	clickHandler: function( e ) {
		if( this.isRunning )
			return;
		
		var t = this;

		if( !$( e.currentTarget ).hasClass( this.options.selected ) ) {
			this.isRunning = true;

			this.currentItem.removeClass( this.options.selected )
			var currentItemId = this.getCardId( this.currentItem );
			this.currentItem = $( e.currentTarget );
			var positionForPointer = this.currentItem.parent().offset();

			$( e.currentTarget )
				.addClass( this.options.selected )
			var itemId = this.getCardId( e.currentTarget );
			$( this.options.pointer )
				.animate( { top: (positionForPointer.top - this.pointerParentPosition.top - 2) + 'px' }, this.options.speed );
			$( '#'+currentItemId )
				.css({
					zIndex: 5
				})
				.animate( { left: '691px' }, this.options.speed );
			$( '#'+itemId )
				.css({
					zIndex: 10
				})
				.animate( { left: '0' }, this.options.speed, function(){ t.isRunning = false;  } );
		}
	},
	
	getCardId: function( item ){
		return $( item ).attr( 'id' ).replace( this.itemIdRegexp, this.options.cardIdPrefix );
	}
}
