//rotation.js
/* 20110909 jun fujimura */
(function(){
	function promotion(){
		document.write('<style>#top .promotion .loading { display:block; }</style>');
		jQuery.event.add(window,'load',function(){
			//main image rotation effect
			var imgs       = [ 
					'./img/promotion/idx_pic_01.jpg',
					'./img/promotion/idx_pic_02.jpg',
					'./img/promotion/idx_pic_03.jpg',
					'./img/promotion/idx_pic_04.jpg',
					'./img/promotion/idx_pic_05.jpg',
					'./img/promotion/idx_pic_06.jpg',
					'./img/promotion/idx_pic_99.jpg'
				],
				$loading = $('#contents .promotion .loading');

			// ImageLoading
			new ImageLoader(imgs, 6000, function(arr){
				// request succes
				if(arr.length===0){
					$loading.fadeOut(800,function(){
						$loading.remove();
					});
					return false;
				}
				// create HTML
				var html = '';
				for(var i=0, l=arr.length; l>i; i++){
					html += '<li><img src="'+arr[i].src+'" alt="" /></li>';
				}
				$('#contents .promotion .pictures').empty().append(html);
				$('#contents .promotion .pictures li:not(:first-child)').css('opacity','0');

				//loading wrapper fadeout
				$loading.animate( { top : 0 }, 1000, function(){
					$(this).animate( { opacity:'0' }, 1000, 'easeOutQuart', function(){
						$loading.remove();
						start();
					});
				});
			}, function(){
				// timeout
				$loading.fadeOut(1500,function(){
					$loading.remove();
				});
			});

			function start(){
				var $li      = $('#contents .promotion .pictures li'),
					$lis     = [],
					length   = $li.length-1,
					current  = 0,
					timeid   = 0,
					wm       = { started : true, focusflg : true },
					config   = {
						fadeIn       : 1000,
						fadeOut      : 1000,
						fadeInDelay  : 0,
						fadeOutDelay : 0,
						interval     : 3000
					};

				init();

				function init(){
					for(var i=0, l=$li.length; l>i; i++){
						$lis[i] = $('#contents .promotion .pictures li:nth-child('+(i+1)+')');
					}
					start();
				}

				function start(){
					wm.started = true;
					timeid = setTimeout(rotation,config.interval);
				}

				function rotation(){
					//fadeout
					if (current < length) {
						$lis[current].css('z-index','6')
							.delay(config.fadeOutDelay)
							.fadeTo(config.fadeOut,0,function(){
								$(this).css('z-index','2');
							});
					}
					else {
						$lis[current].css('z-index','6');
					}
					//next
					current = current+1;
//					if( current > length ){
//						current=0;
//					}
					//fadein
					$lis[current].css({'z-index':'5','opacity':'1'});

					if( current >= length ){
						return;
					}
					if(wm.focusflg) start();
					else wm.started = false;
				}

				function windowOnfocusHandler(){
					wm.focusflg = true;
					if(!wm.started) start();
				}
				function windowOnBlurHandler(){
					wm.focusflg = false;
				}
				$(window).bind( 'blur', windowOnBlurHandler);
				$(window).bind( 'focus', windowOnfocusHandler);
			}
		});
	}

	promotion();

})();

