$( document ).ready( function() 
{
	///////////////////////////////////////////////////////////////////////////
	/// moving top clouds /////////////////////////////////////////////////////
/*/
	var cloudTopperAnimate = function( item, time, limit ) 
	{
		if( item.length > 0 )
		{
			var bp = item.css( 'background-position' ).split( ' ' );
			bp[0] = parseInt( bp[0] );
			bp[1] = parseInt( bp[1] );
			var bp_rand = Math.floor( Math.random() * 10000 );
			{
				//
				bp[0] += -1;
				//
				if( bp_rand % 9 == 1 ) bp[1] += 1;
				if( bp_rand % 8 == 1 ) bp[1] -= 1;

				bp[1] = Math.min( limit+1, bp[1] );
				bp[1] = Math.max( limit-1, bp[1] );
			}
			var bp_string = bp[0] +'px '+ bp[1] +'px';

			item.animate( {backgroundPosition: bp_string}, time, function() { cloudTopperAnimate(item, time, limit); } ); 
		}
	}

	var bg1 = $( '#topper' );
//	cloudTopperAnimate( bg1, 200, -25 );

	var bg2 = $( '#topper #topper-bg' );
//	cloudTopperAnimate( bg2, 300, -35 );
/**/	
	///////////////////////////////////////////////////////////////////////////
	/// moving clouds /////////////////////////////////////////////////////////

	var cloudContent = {
		items: null,

		init: function( no )
		{
			var BG = $( '.BG' );
			this.items = new Array( no );
			for( var i = 0; i < no; ++i )
			{
				this.items[i] = this.create();
				BG.append( this.items[i] );
			}
			return this;
		},
		move: function( time )
		{
			rand = Math.random();
			for( var i = 0; i < this.items.length; ++i )
			{
				var t = parseInt( this.items[i].css('top') );
				var l = parseInt( this.items[i].css('left') );
				var w = parseInt( this.items[i].css('width') );
				if( l + w > 0 )
				{
					var rand_tmp = Math.floor(rand * Math.pow(10, i+1) % 10);
					if( rand_tmp == 7 ) t += 1;
					else if( rand_tmp == 3 ) t -= 1; 

					this.items[i].css( {
						'top': t +"px",
						'left': (l-parseInt(this.items[i].attr('rel'))) +"px"
					} );
				}
				else
				{
					this.items[i].fadeOut();
					this.items[i] = this.create( this.items[i] );
				}
			}
			var cc = this;
			setTimeout( function() { cc.move(time); }, time );
		},
		create: function( cloud )
		{
			rand = Math.random();
			var rand_t = (rand * 1000 % 100)/100;
			var rand_l = (rand * 100000 % 100)/100;
			var rand_s = Math.max( ((rand * 10000000 % 100)/100), 0.5 );

			var is_new = false;
			if( cloud === undefined )
			{
				var cloud = $( '<img src="'+ HTTP_ADDRESS +'site/layout/images/cloud.png" class="cloud" />' );
				is_new = true;
			}

			var left = is_new ? rand_l * $(document).width() : $(document).width();
			cloud.css( {
				'width': (rand_s * 128) +"px",
				'height': (rand_s * 128) +"px",
				'top': (rand_t * 300 + 200) +"px",
				'left': left +"px",
				'opacity': Math.max( rand, 0.5 )
			} );
			cloud.attr( 'rel', Math.floor(rand * 100 % 3)+1 );
			cloud.fadeIn( 'fast' );
			return cloud;
		}
	};

	var cc = cloudContent.init( 15 );
	cc.move( 100 );

});
