(function($){
	
	var list = (function(){

		var main = $('body.main'), // main page
			list = $('#list'),	   // 리스트 dom id
			listData,		       // 리스트 json 
			totalCount,		       // 리스트 총 개수
			orgCount = 6,          // 한 페이지당 노출할 개수  
			listCount,	           // 불러온 리스트 개수
			totalPages,		       // 총 페이지 개수
			currentPages,          // 현재 페이지
			liCount = 0,	       // li index 계산
			maskWidth;			   // 오버시 마스크 사이즈
		
		var jsonUrl = 'http://localhost:8082/front/withrush/listJson.do';
		
		var listJSON = {};

		// 1. check #list
		var checkList = function(){
			if(list.size() > 0){
				getListJson();
			} else {
				return;
			}
		},
		
		// 2. get json
		getListJson = function(){
			var url=jsonUrl; // json URL

			var nextPage = 1;
			try{
				if(parseInt(currentPages) > 0){
					nextPage = parseInt(currentPages) + 1;
				}
			}catch(e){}
			
			$.ajax({      
				type:'post',  
				url:url,      
				data:{"page":nextPage},
				dataType :'json',
				success:function(data){
					listJSON = data;
					listData = listJSON.list;
					totalCount = listJSON.totalCount;
					totalPages = listJSON.totalPage;
					currentPages = listJSON.page;
					listCount = listData.length;
					init();
				},  
				error:function(e){
					//alert(e.responseText);
				}  
			});
		},
		// 3. add ul
		init = function(){
			var ul = '<ul></ul>';
			if(list.find('ul').size() == 0) list.append($(ul));
			
			listData = listJSON.list;
			totalCount = listJSON.totalCount;
			totalPages = listJSON.totalPage;
			currentPage = listJSON.page;
			listCount = listData.length;
			
			addList(currentPages);
		},

		setIsotope = function(){
			var container = list.find('ul');

			maskSize();
			setList();
		},

		setList = function(){
			var container = list.find('ul');
			container.isotope({
					itemSelector : '.items',
					layoutMode : 'fitRows',
					resizable : true,
					resizesContainer : true,
					animationEngine : 'jquery',
					animationOptions: {
						duration: 100,
						easing: 'easeInOutQuad',
						queue: false
					}
				});
		},

		reLayout = function(){
			setIsotope();
			$(window).smartresize(function(){
				maskSize();

				// IE7 & IE8
				if (navigator.appVersion.indexOf("MSIE 7.0")>=0 || navigator.appVersion.indexOf("MSIE 8.0")>=0) { 
					setTimeout(function(){
						list.find('ul').isotope({
							masonry: {itemSelector : '.items'}
						});
					}, 500);
				} else {
					return;
				}
			});
		},

		// 4. default list
		addList = function(currentPage){
			var container = list.find('ul'),
				liElement = '<li class="items">'
								+'	<div class="items_wrapper">'
								+'		<p class="loading"><img src="'+__webRootUrl+'/front/images/withrush/loading.gif"></p>'
								+'	</div>'
								+'</li>';
				
				// set count
				if(totalCount == 0 || totalCount == undefined || listData == undefined) {
					listCount = 1;
					liElement = '<li class="nolist">목록이 없습니다.</li>';

					list.find('ul').append(liElement);
				} else {
					// set isotope
					setIsotope();

					// add li
					for(var i=0; i<listCount; i++){
						container.isotope('insert', $(liElement));
					}
					setTimeout(loadImg, 300);
	
					// add moreBtn
					if(parseInt(totalPages) > parseInt(currentPages)){
						addBtnMore();
					} else if(parseInt(currentPages) >= parseInt(totalPages)) {
						removeBtnMore();
					}
				}
		},		

		// 5. load images
		loadImg = function() {
            var img = new Image(),
				imgArr = [];

			for(var i=0; i<listCount; i++){
				img.src = listData[i].imgsrc;
				imgArr.push($(img));
			}
            imgArr.onload = LoadData();
        },
		
		// 6. load data & add list
        LoadData = function() {
			var objIndex,
				obj,
				info,
				liElement,
				loading;

			for(var i=0; i<listCount; i++){
				objIndex = i + (orgCount * liCount),
				obj = list.find('li').eq(objIndex).find('.items_wrapper'),
				info = listData[i]
				loading = $('.loading');
				
				// info.url이 irush홈페이지의 url인지확인.
				var isOurUrl = true;
				try{
					isOurUrl = (info.url.indexOf(__webRootUrl) > -1);
				}catch(e){}
				
				// url이 외부사이트이고 트렌드데스크나 위드러시일 경우에는 새창뜨기로 한다.
				if(!isOurUrl && 
						( __webRootUrl.indexOf("/trenddesk/") || __webRootUrl.indexOf("/withrush/") )){
					liElement = '<a href="'+ info.url +'" target="_blank">'
					+'	<h2>'+ info.subject +'</h2>'
					+'	<span class="txt">'+ info.summary +'</span>'
					+'	<span class="img"><img src="'+ info.imgsrc +'" alt="'+ info.imgalt +'"></span>'
					+'</a>';
					
				} else {
					liElement = '<a href="'+ info.url +'">'
					+'	<h2>'+ info.subject +'</h2>'
					+'	<span class="txt">'+ info.summary +'</span>'
					+'	<span class="img"><img src="'+ info.imgsrc +'" alt="'+ info.imgalt +'"></span>'
					+'</a>';
				}

				obj.find(loading).remove();
				obj.append($(liElement))
					.css({
						'position' : 'absolute'
					});
				startPosition(objIndex);
				addBoxEffect(objIndex);
			};
			setTimeout(moveFocus, 1000);
        },
		
		startPosition = function(index){
			var positionArr = [],
				index = index,
				obj = list.find('li').eq(index).find('.items_wrapper'),
				position = ['top', 'bottom', 'left', 'right'],
				randomNum = Math.floor(Math.random()*4),
				direction = position[randomNum];
				positionArr.push(position[randomNum]);
				
			switch(direction){
				case 'top':
					obj.css('top', -maskWidth*2).css('opacity', 0);
					break;
				case 'bottom':
					obj.css('top', maskWidth*2).css('opacity', 0);
					break;
				case 'left':
					obj.css('left', -maskWidth).css('opacity', 0);
					break;
				case 'right':
					obj.css('left', maskWidth).css('opacity', 0);
					break;
				default :
					break;
			}
			stopPosition(index, direction);
		},

		stopPosition = function(index, direction){
			var index = index,
				obj = list.find('li').eq(index).find('.items_wrapper'),
				direction = direction,
				delayNum = Math.floor(Math.random()*300),
				duration = 500;
			
			switch(direction){
				case 'top':
					obj.delay(delayNum).animate({top:'0px', 'opacity':1}, duration, 'easeOutQuart');
					break;
				case 'bottom':
					obj.delay(delayNum).animate({top:'0px', 'opacity':1}, duration, 'easeOutQuart');
					break; 
				case 'left':
					obj.delay(delayNum).animate({left:'0px', 'opacity':1}, duration, 'easeOutQuart');
					break;
				case 'right':
					obj.delay(delayNum).animate({left:'0px', 'opacity':1}, duration, 'easeOutQuart');
					break;
				default :
					break;
			}
		},

		maskSize = function(){
			if($(window).width() < 1025) {
				maskWidth = 270;
			} else if($(window).width() >=1025) {
				maskWidth = 290;
			}
		},

		addBoxEffect = function(index){
			if (navigator.userAgent.match(/iPad|iPhone|Android/) == null) {
					var index = index,
					obj = list.find('li').eq(index).find('a'),
					duration = 500;
				
				obj.bind({
					'mouseover keyup': function(){
						$(this).find('img').stop().animate({top:-maskWidth}, duration, 'easeOutQuart')
					},
					'mouseleave focusout': function(){
						$(this).find('img').stop().animate({top:'0px'}, duration, 'easeOutQuart')
					}
				});
			} ;
		},

		addBtnMore = function(){
			var addButton = '<p class="btn_more"><a href="#list">더보기</a></p>';
			if($('.btn_more').size() == 0) {
				list.children('ul').after($(addButton))
				setTimeout(addBtnMoreEvent, 100);
			} else {
				return;	
			};
		},

		addBtnMoreEvent = function(){
			var moreBtn = $('.btn_more > a');

			moreBtn.bind('click', function(event){
				getListJson();
				scrollMove();
				liCount++;
			});
		},

		moveFocus = function(){
			var objIndex = (orgCount * (liCount)),
				obj = list.find('li').eq(objIndex),
				count = obj.size();
			
			if(currentPage == 1) return;
			$('#list').find('li').eq(objIndex).find('a').focus();
		},
		
		removeBtnMore = function(){
			var moreBtn = $('.btn_more');
			if($('.btn_more').size() > 0) moreBtn.css({display: 'none'});
		},
			
		scrollMove = function() {
			var liHeight = list.find('li').height(),
				containerHeight = list.find('ul').height(),
				searchHeight = $('.ourwork_top').outerHeight(),
				scrollHeight,
				margin = 120;

			if($(document).width() < 639){
				margin = 0;
				if($('.ourwork').size() > 0) {margin = 130 - searchHeight;}
			} else if($(document).width() >= 640 && $(document).width() < 1025) {
				margin = 30;
				if($('.ourwork').size() > 0) {margin = 115 - searchHeight;}
			} else if ($(document).width() >= 1025) {
				margin = 120;
				if($('.ourwork').size() > 0) {margin = 105 - searchHeight;}
			}
			
			scrollHeight = containerHeight + liHeight - margin;			
			$('html, body').stop().animate({scrollTop: scrollHeight}, 800,'easeInOutQuad');
		};
		
		//  변수 setter
		setJsonUrl = function(url) {
			jsonUrl = url;
		};
		
		return {
			checkList : checkList,
			reLayout : reLayout,
			setJsonUrl : setJsonUrl
		};
	})();

	$(document).ready(function(){
		try{list.setJsonUrl(__jsonUrl);}catch(e){}
		list.checkList();
		list.reLayout();
	});	

}(jQuery));