jQuery.noConflict();

(function($) { 
	$(function() {

		//$().framerate();

		// Defaultti easing
		//jQuery.easing.def = "easeOutCubic";
		jQuery.easing.def = "easeOutExpo";

		// doc_height päivitetään ikkunan resizen yhteydessä!
		var doc_height = $(window).height(),
			win_width = $(window).width(),
			img_cont = $('#image-container').css( { 'height': doc_height, display: 'none' } ),
			imgs = {  },
			current_image = 0,

			// Päivitetään seuraavassa loopissa
			last_image_num = 0,
			transition_speed = 2000,
			all_img_width_sum = 0,
			currently_animating = false,
			thumbs_up = false,
			$contentBox = null,
			quicklook_active = false,
			current_thumb_location = 0,
			hide_main_cont = false;

		var thumb_scroll_pos = 0;
		
		$('#prev-big, #next-big').css( 'height', doc_height );

		$('#prev-big').mouseout(function(){
			$('#cursor-prev').hide();
			return false;
		});
		$('#prev-big').mouseenter(function(){
			$('#cursor-prev').show();
			return false;
		});
		$('#prev-big').mousemove(function(e){
			$('#cursor-prev').css('left', e.clientX - 20).css('top', e.clientY + 7);
		});

		$('#next-big').mouseout(function(){
			$('#cursor-next').hide();
			return false;
		});
		$('#next-big').mouseenter(function(){
			$('#cursor-next').show();
			return false;
		});
		$('#next-big').mousemove(function(e){
			$('#cursor-next').css('left', e.clientX - 20).css('top', e.clientY + 7);
		});

		$('body, #wrapper').css( 'height', doc_height+'px' );
		$('#site-nav, #site-nav-hider').css( 'height', ( doc_height - parseInt( $('#site-nav').css('paddingTop') ) )+'px' );

		$('#all-images').css( { 'left': '300px', 'width': $(window).width() - 340, 'top': '-'+$('#all-images').height()+'px' } );

		$img_cont_children = img_cont.children( 'div' );
		$img_cont_children_length = $img_cont_children.length;

		var thumbs_are_loading = false;

		// Kaikki kuvat containereihinsa
		$img_cont_children.each( function( i, item  )
		{
			imgs[i] = { id: this.id };
			var img = $("<img />")
					.attr('src', item.title)
	      			.load(function(a)
	      			{
      					scale_image( this );
         				imgs[i].width = this.width;
         				imgs[i].height = this.height;
         				this.id = item.id;
         				this.alt = $(item).attr('alt');

						// Replacetaan div img:llä
         				// Takaa sen, että kuvat tulee oikeassa järjestyksessä vaikka
         				// ladataankin asynkisti


						$('#'+item.id).replaceWith( this );
         				$('#'+item.id).wrap('<div />').parent().css( { 'height': $(this).height() } ).animate( {'width': $(this).width() } );
         				
         				// Jos id niin appentoidaan span
         				if ( this.alt !== '' && this.alt !== 'undefined' )
         				{
         					// Splitataan nimi ja maili erikseen
         					var _split = this.alt.split(';');
         					$('#'+item.id).parent().append('<span id="big-image-alt-'+item.id+'" class="big-image-alt"><a href="mailto:'+_split[1]+'">'+_split[0]+'</a></span>');
         				}

						last_image_num++;
						all_img_width_sum += this.width;
         				
         				// Keskitä kuvat ensimmäisen kuvan leveyden perusteella
         				if ( i === 0 )
         				{
		      				//img_cont.css( { 'left': (win_width / 2) - ( $(this).width() / 2 ) } );
         					
         					if ( !hide_main_cont )
         					{
         						img_cont.fadeIn();
         					}
         				}
	      			});

	      		if ( i === Math.round($img_cont_children_length/2) && !thumbs_are_loading )
	      		{
	      			thumbs_are_loading = true;
	      			load_thumbs();
	      		}
		});

		$('#wrapper').removeClass('loading');

		/**
		 *	Skaalaa kuvan oikean kokoiseksi
		 *
		 *	@param img object
		 *	@throws img object
		 */
		function scale_image( _img, _wish_height )
		{
			var _ratio = _img.width / _img.height;
			
			if ( _wish_height !== undefined )
			{
				_img.height = _img.height;
				_img.width = _img.width;
				$(_img).css(
				{
					width: Math.round(_wish_height * _ratio),
					height: _wish_height
				});
			}
			else
			{
				_img.height = doc_height;
				_img.width = Math.round(doc_height * _ratio);
			}

			return _img;
		}

		var hide_timer = window.setTimeout(function() { $('#site-nav-hider').fadeOut('slow'); }, 2000),
			mouse_over_nav = false;

		/*$('#site-nav').mouseenter(function(e)
		{
			$('#site-nav-hider').fadeIn();

			window.clearTimeout(hide_timer);

			hide_timer = window.setTimeout(function() { $('#site-nav-hider').fadeOut('slow'); }, 2000);
		});*/

		$(document).mousemove(function(e){
     		if ( e.pageX < 270 )
     		{
     			$('#site-nav-hider').fadeIn();

				window.clearTimeout(hide_timer);

				hide_timer = window.setTimeout(function() { $('#site-nav-hider').fadeOut('slow'); }, 5000);
     		}
  		});

		/**
		 *	Window objektin resize
		 *
		 */
		$(window).resize( function(e)
		{
			// Scalea kuviin vain joka 200 ms
			// Muuten menee liian nopiasti :)
			setTimeout( function()
			{
				if ( !thumbs_up )
				{
					var _img_cont_place = '0px';

					all_img_width_sum 	= 0;
					doc_height			= $(window).height();

					img_cont.children( 'div' ).each( function( i, item )
					{
						scale_image( item );

						imgs[i].width = item.width;
						imgs[i].height = item.height;

						all_img_width_sum += item.width;

						if ( i === current_image && current_image !== 0 )
							_img_cont_place = '-'+(all_img_width_sum - imgs[i].width)+'px';
					});

					img_cont.css( { 'left': _img_cont_place, 'height': doc_height } );
					$('#site-nav').css( 'height', ( doc_height - parseInt( $('#site-nav').css('paddingTop') ) )+'px' );
				}
				else
				{
					if ($('#quicklookWindow:visible'))
					{
						$('#quicklookWindow').css({ 'width': $(window).width(), 'height': $(window).height() });
					}

					$('#all-images').css( 'width', $(window).width() - parseInt( $('#all-images').css('left') ) );
				}
			}
			, 200 );
		});
		
		


		/**
		 *	Navigoinnin click bind
		 *
		 */
		$( '#prev, #prev-big' ).bind( 'click', function(e)
		{	
			control.slide_to_image( current_image-1 );

			e.preventDefault();
		});

		$( '#next, #next-big' ).bind( 'click', function(e)
		{	
			control.slide_to_image( current_image+1 );

			e.preventDefault();
		});

		$( '#quicklook-next' ).live( 'click', function(e)
		{	
			var _id = parseNumber( $('#quicklook_img_cont').find('img').attr('id') );
			
			if ( $('#all-images').find('#tpm-image'+_id).parent().next().is('span') )
			{
				control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().prevAll('.thumb-nav').eq(0).next('a').find('img').attr('id')) );
			}
			else
			{
				control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().nextAll('.quicklook').eq(0).find('img').attr('id')) );
			}

			e.preventDefault();
		});

		$( '#quicklook-prev' ).live( 'click', function(e)
		{	
			var _id = parseNumber( $('#quicklook_img_cont').find('img').attr('id') );
			
			if ( $('#all-images').find('#tpm-image'+_id).parent().prev().is('div') )
			{
				control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().nextAll('span').eq(0).prev('a').find('img').attr('id')) );
			}
			else
			{
				control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().prevAll('.quicklook').eq(0).find('img').attr('id')) );
			}
			
			e.preventDefault();
		});

		var $cont = $( '.header-cont' );
		$cont.bind( 'click', function(e)
		{
			$(this).toggleClass('open').next( '.subnav' ).slideToggle();

			$cont.not( $(this) ).each(function(i, item)
			{
				$(this).removeClass('open').next( '.subnav' ).slideUp();
			});

			e.preventDefault();
		});

		// Avataan oikea kategoria
		$('.active-cat').parent().toggleClass('open').next( '.subnav' ).show();

		/**
		 *
		 *	
		 *
		 */
		$('.thumbnails').bind( 'click', function(e)
		{
			$('#photographers-cont a').each(function(i, item)
			{
				if ( $(item).hasClass('active') )
				{
					thumb_scroll_pos = i;

					return false;
				}
			});

			trigger_thumbnails();

			e.preventDefault();
		});

		function trigger_thumbnails( )
		{
			if ( !thumbs_up )
				thumbs_up = true;
			else
				thumbs_up = false;
			
			//img_cont.hide();

			if ( thumbs_up )
			{
				$('#prev-big, #next-big').hide();
				$('#bottom-stuff').slideUp();

				$('#thumbs-text').text('Big images');
				$('#thumbs-image').addClass('bigs');

				$('html, body').addClass('show-overflow');

				img_cont.slideUp(function()
				{
					var _top = 0;

					$('#all-images').show();

					if ( thumb_scroll_pos !== 0 )
					{
						_top = $('#group-'+thumb_scroll_pos).position().top;
						current_thumb_location = thumb_scroll_pos;
					}

					$('#all-images').show().animate( { 'top': 0, 'opacity': 1 }, 1000, function()
					{
						$(document).scrollTop( _top );
					});
				
				});

				if(window.location.hash)
				{
					scroll_to_anchor( $('#contact-info') );
				}

				$('body').append('<div id="quicklookWindow"></div><div id="quicklookBox"></div>');
		
				$contentBox = $('#quicklookBox');
			}
			else
			{
				var _cur_open_cat = $('.header-cont.open').next('.subnav').find('h3').eq(current_thumb_location).find('a').attr('href');

				if ( _cur_open_cat !==  $('.header-cont.open').next('.subnav').find('h3 a.active').attr('href') )
				{
					window.location = $('base').attr('href')+_cur_open_cat;
				}

				$('#bottom-stuff').slideDown();
				$('#prev-big, #next-big').show();
				$('#thumbs-text').text('Thumbnails');
				$('#thumbs-image').removeClass('bigs');

				$('html, body').removeClass('show-overflow');

				$('#all-images').animate( { 'top': '-300px', 'opacity': 0 }, 500, function(){ $(this).hide(); img_cont.slideDown(); } );
			}
		}

		function load_thumbs()
		{
			// Jos löytyy urlista hash #open-thumbs
			if(window.location.hash === '#open-thumbs')
			{
				window.location.hash = '';
				hide_main_cont = true;
				trigger_thumbnails();
			}

			var $c = $('#all-images').children( 'div.floating-image:not(.do-not-include)' );

			$c.each( function( i, item  )
			{
				var d = new Date();
				var cache = d.getTime();

				var item_alt = $(item).attr('alt');

				var _classes = 'quicklook';

				if ( $(item).hasClass('exclude') )
				{
					_classes += ' exclude';
				}

				var img = $("<img />")
				.attr('src', item.title+'/'+cache)
      			.load(function()
      			{
     				scale_image( this, 100 );
     				this.id = item.id;

					// Replacetaan div img:llä
     				// Takaa sen, että kuvat tulee oikeassa järjestyksessä vaikka
     				// ladataankin asynkisti
     				$( '#'+item.id )
         				.wrap('<a class="'+_classes+'" href="'+item.title+'" alt="'+item_alt+'" />')
         				.replaceWith( this );

					$( '#'+item.id ).fadeIn('slow').parent().animate( { 'width': $( '#'+item.id ).width() }, 500 );
				});
			});
		}
				
		$('#image-container, #all-images').delegate( '.quicklook', 'click', function(e)
		{
			openWindow( $(this).children('img'), false );

			e.preventDefault();
		}).delegate( '.quicklook:not(.exclude)', 'mouseenter', function(e)
		{
			if ( $(this).attr('alt') !== '' && $(this).attr('alt') !== 'undefined'  )
			{
				$(this).append('<span class="craphers-name">'+$(this).attr('alt')+'</span>');
			}
			
		}).delegate( '.quicklook:not(.exclude)', 'mouseleave', function(e)
		{
			if ( $(this).attr('alt') !== '' && $(this).attr('alt') !== 'undefined' )
			{
				$(this).find('.craphers-name').remove();
			}
		});


		/**
		*	function openWindow
		*/
		function openWindow( $_img, _show_contacts )
		{
			if ( !_show_contacts )
			{
					
				quicklook_active = true;

				var _img_height = $_img.attr('height'), _img_width = $_img.attr('width');
				var _imageBoxTopPadding = parseInt( $contentBox.css('paddingTop') );
				var _imageBoxLeftPadding = parseInt( $contentBox.css('paddingLeft') );
				var _img_proportion_scale = _img_height / _img_width;

				var _img_id = parseInt( $_img.attr('id').replace('tpm-image', '') );
				
				var _img_zoom = 100;
				
				$('#quicklookWindow').hide().css({ 'width': $(window).width(), 'height': $(window).height() }).fadeIn('slow');
				//$contentBox.hide().css({ 'marginTop': Math.round(0 - $('#quicklookBox').height() / 2), 'marginLeft': Math.round(0 - $('#quicklookBox').width() / 2) });

				// If window is larger than image, proportianaly scale it
				if (_img_height >= $(window).height())
				{
					_img_zoom = _img_height;
					_img_height = Math.round($(window).height() - 100);
					_img_width = Math.round(($(window).height() - 100) / _img_proportion_scale);
					
					_img_zoom = Math.round((_img_height / _img_zoom) * 100);
				}

				/*$contentBox
				.css({
					// Calculate center point for box. Minus the top and left padding
					marginTop: Math.round(0 - _img_height / 2 - _imageBoxTopPadding),
					marginLeft: Math.round(0 - _img_width / 2 - _imageBoxLeftPadding),
					width: 20,
					height: 20
				}).fadeIn('fast');*/

				var img = $("<img />")
					.attr('src', $('base').attr('href')+'binary/image/thumbnailer/-/fid/'+_img_id+'/height/900')
	      			.load(function()
	      			{
	      				// Jos lataus ready
	      				//if ( this.complete )
	      				//{
		      				//$(this).hide();
		      				//scale_image( this, $(window).height() );

		      				if (this.height >= $(window).height())
							{
								var _ratio = this.width / this.height;

								this.height = doc_height - 140;
								this.width = Math.round(doc_height * _ratio) - (140 * _ratio);
							}
							
							if ( this.width >= ($(window).width() - 200) )
							{
								var _ratio = this.height / this.width;

								this.width = $(document).width() - 200;
								this.height = Math.round($(document).width() * _ratio) - (200 * _ratio);
							}


							this.alt = $_img.parent().attr('alt');

		         			$contentBox.html( this );
		         			
		         			$(this).wrap('<div id="quicklook_img_cont" />').fadeIn().attr('id', parseNumber( $_img.attr('id') ));

							$contentBox.append('<div id="quicklook-nav-cont"><a href="#" id="quicklook-prev" /><a href="#" id="quicklook-next" /></div>').fadeIn();

							$('#quicklook-nav-cont').css('left', win_width/2 - 50).fadeIn();
							
		         			// IE prkl ei tajua tätä ketjutettuna ylempänä!
		         			$contentBox.css({
								// Calculate center point for box. Minus the top and left padding
								marginTop: Math.round(0 - this.height / 2 - _imageBoxTopPadding - 40)+'px',
								marginLeft: Math.round(0 - this.width / 2 - _imageBoxLeftPadding)+'px',
								width: this.width,
								height: doc_height - 80
							})

		         			/*if ( parseNumber($('#all-images .quicklook:last img').attr('id')) === parseNumber( $_img.attr('id') ) )
							{
	 							$('#quicklook-next').hide();
							}
							else
							{
								$('#quicklook-next').show();
							}

							if ( parseNumber($('#all-images .quicklook:first img').attr('id')) === parseNumber( $_img.attr('id') ) )
							{
								$('#quicklook-prev').hide();
							}
							else
							{
								$('#quicklook-prev').show();
							}
							*/

						//}
	      			});				
			}
			else
			{
				if ( $('#quicklookWindow').length === 0 )
				{
					$('body').append('<div id="quicklookWindow"></div><div id="quicklookBox"></div>');
					$contentBox = $('#quicklookBox');
				}				
				
				$('#quicklookWindow').hide().css({ 'width': $(window).width(), 'height': $(window).height() }).fadeIn('slow');

				$contentBox
				.css({
					// Calculate center point for box. Minus the top and left padding
					/*marginTop: Math.round(0 - $('#contact-info').height() / 2),
					marginLeft: Math.round(0 - 790 / 2),
					width: 790,
					height: $('#contact-info').height(),
					backgroundColor: 'white',
					overflow-y: 'scroll'*/

					// Calculate center point for box. Minus the top and left padding
					marginTop: Math.round(0 - 500 / 2),
					marginLeft: Math.round(0 - 830 / 2),
					width: 830,
					height: 500,
					backgroundColor: 'white',
					overflowY: 'scroll'
				})
				.html( $('#contact-info').clone().css( 'display', 'block' ) ).fadeIn('fast');

			}
		}

		/**
		*	function closeWindow
		*/
		function closeWindow()
		{	
			quicklook_active = false;

			$('#quicklookWindow').fadeOut('fast', function(){ $(this).hide(); });

			$('#quicklookBox').fadeOut('fast',
			    	function()
			    	{
			    		$('#quicklookBox').hide().html('').css('opacity', 1);
			    	}).css('background', 'none');

		}

		/**
		 *
		 * QuicklookBox delegates
		 *
		 */
		$('#quicklook_img_cont').live('mouseenter', function(e)
		{
			if ( $(this).find('img').attr('alt') !== '' && $(this).find('img').attr('alt') !== 'undefined' && $(this).find('img').attr('alt') !== undefined )
			{
				var _split = $(this).find('img').attr('alt').split(';');
				$(this).append('<span style="width: '+$(this).width()+'px; left: 0; bottom: 0;" class="craphers-name"><a href="mailto:'+_split[1]+'">'+_split[0]+'</a></span>');
			}
			
		}).live('mouseleave', function(e)
		{
			if ( $(this).find('img').attr('alt') !== '' && $(this).find('img').attr('alt') !== 'undefined' )
			{
				$(this).find('.craphers-name').remove();
			}
		});

		$('#quicklookWindow').live('click', function()
		{	
			closeWindow();
		});

		$('.big-image-alt').live( 'mouseenter', function(e)
		{
			_alt_over = true;
		}).live( 'mouseleave', function(e)
		{
			_alt_over = false;
		});

		$('.show-contacts').bind( 'click', function(e)
		{
			openWindow( $('#contact-info'), true );

			e.preventDefault();
		});

		$('.jump-to a').bind( 'click', function(e)
		{
			scroll_to_anchor( $(this) );

			e.preventDefault();
		});

		function scroll_to_anchor( _el )
		{
			var $anchor = _el;

			$anchor = $anchor.attr('href').replace('#', '');

			current_thumb_location = parseNumber($anchor);
				
            $('html, body').stop().animate({
                scrollTop: $('#'+$anchor).offset().top
            }, 750,'easeInOutExpo');
            //_event.preventDefault();
           
		}

		$(window).bind('keyup', function(e)
		{
			if ( quicklook_active )
			{
				var _id = parseNumber( $('#quicklook_img_cont img').attr('id') );

				switch (e.keyCode)
				{
					case 37:
						control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().prev('a').find('img').attr('id')) );
						e.preventDefault();
					break;

					case 39:
						control.quicklook_image( parseNumber($('#all-images').find('#tpm-image'+_id).parent().next('a').find('img').attr('id')) );
						e.preventDefault();
					break;
				}
			}
			else if( !quicklook_active && !thumbs_up )
			{
				switch (e.keyCode)
				{
					case 37:
						control.slide_to_image( current_image-1 );
						e.preventDefault();
					break;

					case 39:
						control.slide_to_image( current_image+1 );
						e.preventDefault();
					break;
				}
			}
				

		});

		/**
		 *
		 *	Image slider master singleton controller!!
		 *
		 *	@function slide_to_image
		 *	@function handle_prev_next
		 *
		 */
		var control = {
			
			slide_to_image: function( _id )
			{
				_id = _id === -1 ? (last_image_num-1) : _id;
				_id = _id > (last_image_num-1) ? 0 : _id;

				var $_img 			= $('#image'+_id).parent();
					_left_pos 		= $_img.position().left;
				
				if ( _id === 0 )
				{
					_left_pos = 0;
				}
				else
				{
					_left_pos = ( win_width / 2 - _left_pos ) - $_img.width() / 2;
				}
		
				img_cont.stop().animate(
					{
						left: _left_pos
					}, transition_speed);
				
				current_image = _id;
			},

			quicklook_image: function( _id )
			{
				/*if ( parseNumber($('#all-images .quicklook:last img').attr('id')) === _id )
				{
					$('#quicklook-next').fadeOut();
				}
				else
				{
					$('#quicklook-next').fadeIn();
				}

				if ( parseNumber($('#all-images .quicklook:first img').attr('id')) === _id )
				{
					$('#quicklook-prev').fadeOut();
				}
				else
				{
					$('#quicklook-prev').fadeIn();
				}
				*/

				$('#quicklook_img_cont img').fadeOut();
				
				var _imageBoxTopPadding = parseInt( $contentBox.css('paddingTop') );
				var _imageBoxLeftPadding = parseInt( $contentBox.css('paddingLeft') );

				var img = $("<img />")
					.attr('src', $('base').attr('href')+'binary/image/thumbnailer/-/fid/'+_id+'/height/900')
	      			.load(function(a)
	      			{
	      				//$(this).hide();

	      				if (this.height >= $(window).height())
						{
							var _ratio = this.width / this.height;

							this.height = doc_height - 140;
							this.width = Math.round(doc_height * _ratio) - (140 * _ratio);
						}

						if ( this.width >= ($(window).width() - 200) )
						{
							var _ratio = this.height / this.width;

							this.width = $(document).width() - 200;
							this.height = Math.round($(document).width() * _ratio) - (200 * _ratio);
						}

						this.alt = $('#all-images').find('#tpm-image'+_id).parent().attr('alt');

	         			$('#quicklook_img_cont').html( this ).css({
							width: this.width,
							height: this.height
						});

						$contentBox.css({
							// Calculate center point for box. Minus the top and left padding
							marginTop: Math.round(0 - this.height / 2 - _imageBoxTopPadding - 40)+'px',
							marginLeft: Math.round(0 - this.width / 2 - _imageBoxLeftPadding)+'px',
							width: this.width,
							height: doc_height - 80
						});

	         			$(this).attr('id', _id).fadeIn();
	      			});
			}
			// End control
		}

		function parseNumber( _string )
		{
			return typeof(_string) == 'number' ? _string : parseInt(_string.match(/\d+/));
		}
	});
})(jQuery);
