/*
 * CjSideboard 객체
 * 
 * 우측 CJ Now 영역을 담당한다.
 * 
 * Lee Won-Gyoon <richscript@gmail.com>, <@richscript>, <www.richscript.net>
 * e-motion Corp.
*******************************************************************************/

var CjSideboard = {
	instanceName : "CjSideboard",
	data : [],
	path : {
		data : "/sideboard.data.asp"
	},
	status : {
		isClosed : true
		, isMoving : false
		, isDataLoaded : false
		, isActive : false
		, isReadyForShow : false
		, isMovingForClosed : false
	},
	area : [],
	vars : {
		imageLoadedCount : 0
		, eachWidth : 170
		, currentAreaSize : -1
		, showTimer : null
		, funcAfterClose : null
	},
	
	getScreenW : function() {
		var screenW = $js.browser.screenW();
		/*
		if (!$js.browser.isIE) {
			screenW -= 20;
		}
		*/
		if (this.status.isClosed) {
			screenW -= 880;
		}
		return screenW;
	},
	
	getDataMaxH : function() {
		var maxVal = this.area[0];
		for (var i=0; i<this.area.length; i++) {
			if (this.area[i]>maxVal) {
				maxVal = this.area[i];
			}
		}
		return maxVal;
	},
	
	resize : function() {
		if (!this.status.isMoving) {
			if (this.status.isDataLoaded) {
				this.sortData();
			}
			var screenW = this.getScreenW();
			var tarW = Math.max(screenW,1);
			var tarH = Math.max((this.status.isClosed)? $("#main").outerHeight():this.getDataMaxH()+95, $js.browser.screenH());
			var contentsWidth = Math.max(tarW-50,1);
			$(this.ids.sideboard).stop().css({
				width: tarW
				, height: tarH
			});
			$("#sideboard-contents").stop().css({
				width: contentsWidth
				, height: Math.max(tarH-95,1)
			});
		}
	},
	
	open : function() {
		window.scroll(0,0);
		this.status.isClosed = false;
		this.status.isMoving = true;
		var ui = this.instanceName;
		if ($(this.ids.sideboard).outerWidth()<900) {
			$(this.ids.sideboard).stop().animate({width:900}, 1000, "easeInExpo");
		}
		$(this.ids.root).stop().animate({left:-880}, 1000, "easeInExpo", function() {
			$("#sideboard div.bottom").css("background-position", "right bottom");
			var tarW = window[ui].getScreenW();
			$(window[ui].ids.sideboard).stop().animate({width: tarW}, function() {
				$(window[ui].ids.contents).hide();
				window[ui].status.isMoving = false;
				window[ui].resize();
				$(".toggle-btn-area a").addClass("on").attr("title", "CJ제일제당 Now 닫기").stop().animate({left:0});
				$(".data-layout a").addClass("opened");
			});
			$("#sideboard-contents").stop().css({width: Math.max(tarW-50,1)});
			$(window[ui].ids.goTop).stop().animate({left:840}, "fast");
			$(".toggle-btn-area a").stop().animate({left:-40}, "fast");
		});
	},
	
	close : function(_func) {
		this.vars.funcAfterClose = _func;
		if (!this.status.isMovingForClosed) {
			window.scroll(0,0);
			this.status.isClosed = true;
			this.status.isMoving = true;
			this.status.isMovingForClosed = true;
			var ui = this.instanceName;
			var tarW = this.getScreenW();
			var minW = (tarW>900) ? tarW : 900;
			$("#sideboard-contents").stop().animate({width: Math.max(tarW-50,1)});
			$(this.ids.sideboard).stop().animate({width: minW}, function() {
				$(window[ui].ids.contents).show();
				$("#sideboard-contents").stop().animate({width: Math.max(tarW-50,1)});
				$(window[ui].ids.sideboard).stop().animate({width: tarW}, 1000, "easeInExpo");
				$(window[ui].ids.root).stop().animate({left:0}, 1000, "easeInExpo", function() {
					$(".toggle-btn-area a").removeClass("on").attr("title", "CJ제일제당 Now 열기");
					$(".data-layout a").removeClass("opened");
					$(window[ui].ids.goTop).stop().css({left:880});
					$("#sideboard div.bottom").css("background-position", "-500px bottom");
					//$(window[ui].ids.goTop).show();
					window[ui].status.isMoving = false;
					window[ui].status.isMovingForClosed = false;
					window[ui].resize();
					if (typeof(window[ui].vars.funcAfterClose)=="function") {
						try {
							window[ui].vars.funcAfterClose.apply(window);
						} catch(e) {}
						window[ui].vars.funcAfterClose = null;
					}
				});
			});
			$(this.ids.goTop).stop().animate({left:880}, "fast");
		}
	},
	
	loadData : function() {
		$.ajax({
			context: this,
			type: "get",
			url: this.path.data,
			data: ({
				_temp:(new Date()).getTime()
			}),
			dataType: "text",
			success: function(_s){
				var result = {};
				try {
					result = eval("("+_s+")");
				} catch(e) { }
				if (result.length>0) {
					for (var i=0; i<result.length; i++) {
						this.data.push(result[i]);
						result[i] = null;
					}
				}
				result = null;
			},
			error: function(event, request, settings) {
				alert("[" + event.status + "] CJ Now 데이터를 가져오는 중 오류가 발생했습니다.");
			},
			complete: function() {
				this.printData();
			}
		});
	},
	
	showToggleButton : function() {
		var ui = this.instanceName;
		$(".toggle-btn-area a").stop().animate({left:0,top:95}, function() {
			window[ui].show();
			$(window).bind("scroll resize", function() {
				$(".toggle-btn-area a").stop().animate({left:0,top:$js.browser.scrollY()+95}, 500);
			});
		});
	},
	
	getDataHTML : function(_index) {
		var data = this.data[_index];
		var s = '';
		s += '<div id="data-'+_index+'" class="data-layout">\n';
		s += '<a href="javascript:;"';
		s += ' url="'+data.url.escapeXml()+'"';
		s += ' t="'+data.target.escapeXml()+'"';
		s += ' class="data '+((data.type=="A")?'w320':'w150')+'">\n';
		s += '	<div class="cover"></div>\n';
		s += '	<div><img index="'+_index+'" src="'+data.image.escapeXml()+'" border="0" /></div>\n';
		s += '	<div class="text-box">\n';
		s += '		<div class="text-box-top"></div>\n';
		s += '		<div class="text-box-body">'+data.text+'</div>\n';
		s += '		<div class="text-box-bottom"></div>\n';
		s += '	</div>\n';
		s += '</a>\n';
		s += '</div>\n';
		data = null;
		return s
	},
	
	printData : function() {
		var ui = this.instanceName;
		for (var i=0; i<this.data.length; i++) {
			$("#sideboard-contents").append(this.getDataHTML(i));
			$("#data-"+i+" img").load(function() {
				var index = $(this).attr("index");
				window[ui].imageLoaded(index, "success");
			}).error(function() {
				var index = $(this).attr("index");
				window[ui].imageLoaded(index, "error");
			});
			$("#data-"+i+" a").click(function(e) {
				e.preventDefault();
				var url = $(this).attr("url");
				var target = $(this).attr("t");
				if (url.indexOf("http://")==0) {
					openWindow(url, "_blank", "");
				} else {
					if (window[ui].status.isClosed) {
						location.href = url;
					} else {
						if (url.indexOf("openMenu")>-1) {
							window[ui].close(function() {
								location.href = url;
							});
						} else {
							location.href = url;
						}
					}
				}
			});
		}
	},
	
	imageLoaded : function(_index, _result) {
		this.vars.imageLoadedCount++;
		this.data[_index].isDisplay = (_result=="success") ? true : false;
		if (this.vars.imageLoadedCount==this.data.length) {
			var ui = this.instanceName;
			setTimeout(function() {
				window[ui].showToggleButton();
			}, 1000);
		}
	},
	
	show : function() {
		if (this.status.isActive) {
			clearTimeout(this.vars.showTimer);
			this.status.isReadyForShow = false;
			$("#sideboard-contents").children().first().remove();
			for (var i=0; i<this.data.length; i++) {
				$("#data-"+i).css("display", (this.data[i].isDisplay)?"block":"none").css("visibility", "visible");
				this.data[i].width = (this.data[i].isDisplay) ? $("#data-"+i).outerWidth() : 0;
				this.data[i].height = (this.data[i].isDisplay) ? $("#data-"+i).outerHeight() : 0;
				if (this.data[i].isDisplay) {
					$("#data-"+i).css({
						  left: Math.max(Math.floor(($("#sideboard-contents").width()-this.data[i].width)/3),0)
						, top: Math.max(Math.floor(($("#sideboard-contents").width()-this.data[i].height)/2),0)
					});
					$("#data-"+i+" div.cover").css({
						  width: this.data[i].width-20
						, height:this.data[i].height-20
					});
				}
			}
			this.status.isDataLoaded = true;
			this.sortData();
		} else {
			this.status.isReadyForShow = true;
		}
	},
	
	getMinSortPoint : function(_index) {
		var data = this.data[_index];
		var point = {x:0,y:0};
		var areaIndex = 0;
		if (data.width>this.vars.eachWidth) {
			var minValue = Math.max(this.area[0],this.area[1]);
			for (var i=0; i<this.area.length-1; i++) {
				var maxValue = Math.max(this.area[i],this.area[i+1]);
				if (maxValue<minValue) {
					areaIndex = i;
					minValue = maxValue;
				}
			}
			point.x = areaIndex * this.vars.eachWidth;
			point.y = Math.max(this.area[areaIndex],this.area[areaIndex+1]);
			this.area[areaIndex] = this.area[areaIndex+1] = point.y + data.height;
		} else {
			var minValue = this.area[0];
			for (var i=0; i<this.area.length; i++) {
				if (this.area[i]<minValue) {
					areaIndex = i;
					minValue = this.area[i];
				}
			}
			point.x = areaIndex * this.vars.eachWidth;
			point.y = this.area[areaIndex];
			this.area[areaIndex] += data.height;
		}
		return point;
	},
	
	moveDataTo : function(_index, _x, _y) {
		$("#data-"+_index).stop().animate({left:_x, top:_y}, "slow");
	},
	
	sortData : function() {
		var totalWidth = $("#sideboard-contents").innerWidth();
		var areaSize = Math.floor(totalWidth/this.vars.eachWidth);
		if (this.vars.currentAreaSize!=areaSize) {
			if (areaSize<2) {
				areaSize = 2;
			}
			this.area = [];
			for (var i=0; i<areaSize; i++) {
				this.area.push(0);
			}
			for(var i=0; i<this.data.length; i++) {
				if (this.data[i].isDisplay) {
					var point = this.getMinSortPoint(i);
					this.moveDataTo(i, point.x, point.y);
				}
			}
			this.vars.currentAreaSize = areaSize;
		}
	},
	
	getHTML : function() {
		var s = '';
		s += '<div class="toggle-btn-area">\n';
		s += '	<a href="javascript:;" class="btn-toggle" title="CJ제일제당 Now 열기"></a>\n';
		s += '</div>\n';
		s += '<div class="bottom">\n';
		s += '	<div class="top-right">\n';
		s += '		<div class="top-left">\n';
		s += '			<div class="body-layout">\n';
		s += '				<div id="sideboard-contents">';
		s += '<table style="width:100%;height:600px;" cellpadding="0" cellspacing="0" border="0">\n';
		s += '	<tr>\n';
		s += '		<td align="center">'+$loading.getS()+'</td>\n';
		s += '	</tr>\n';
		s += '</table>\n';
		s += '				</div>\n';
		s += '			</div>\n';
		s += '		</div>\n';
		s += '	</div>\n';
		s += '</div>\n';
		return s;
	},
	
	print : function() {
		$(this.ids.sideboard).html(this.getHTML());
	},
	
	active : function() {
		this.status.isActive = true;
		$(this.ids.sideboard).css({display:""});
		var ui = this.instanceName;
		this.vars.currentAreaSize = -1;
		if (!this.status.isReadyForShow) {
			this.resize();
		} else {
			clearTimeout(this.vars.showTimer);
			this.vars.showTimer = setTimeout(function() {
				window[ui].show();
			}, 3000);
		}
		$(window).bind("resize."+this.instanceName, function() {
			window[ui].resize();
		});
		if (!$js.browser.isIE) {
			$(window).bind("iframeResize."+this.instanceName, function() {
				window[ui].resize();
			});
		}
	},
	
	inActive : function() {
		this.status.isActive = false;
		$(window).unbind("."+this.instanceName);
		$(this.ids.sideboard).css({display:"none"});
	},
	
	initialize : function() {
		this.ids = {
			root : "#main"
			, contents : "#contents"
			, goTop : "#go-top"
			, sideboard : "#sideboard"
		};
		this.print();
		
		var ui = this.instanceName;
		
		$(".toggle-btn-area a").click(function(e) {
			e.preventDefault();
			if (!window[ui].status.isMoving) {
				if (!$(this).hasClass("on")) {
					window[ui].open();
				} else {
					window[ui].close();
				}
			}
		});
	}
};



$(function() {
	CjSideboard.initialize();
	CjSideboard.active();
});

$(window).bind("load", function() {
	CjSideboard.loadData();
});



