if (typeof jQuery != "undefined"){
	function imgpreload(imgs,settings){
		// settings = { each:Function, all:Function }
		if (settings instanceof Function) { settings = {all:settings}; }
	
		// use of typeof required
		// https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description
		if (typeof imgs == "string") { imgs = [imgs]; }
	
		var loaded = [];
		var t = imgs.length;
		var i = 0;
	
		for (i; i<t; i++){
			var img = new Image();
			img.onload = function(){
				loaded.push(this);
				if (settings.each instanceof Function) { settings.each.call(this); }
				if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); }
			};
			img.src = imgs[i];
		}
	}
	
	(function($){		
		/**
		 * jQuery Fn : radioClass
		 */
		$.fn.radioClass = function(css){ 
			return this.siblings().removeClass(css).end().addClass(css);
		};
	
		/**
		 * jQuery Fn : imgpreload
		 * Copyright (c) 2009 Dimas Begunoff, http://www.farinspace.com 
		 */
		
		// extend jquery (because i love jQuery)
		$.imgpreload = imgpreload;

		// public
		$.fn.imgpreload = function(settings){
			settings = $.extend({},$.fn.imgpreload.defaults,(settings instanceof Function)?{all:settings}:settings);

			this.each(function(){
				var elem = this;

				imgpreload($(this).attr('src'),function()
				{
					if (settings.each instanceof Function) { settings.each.call(elem); }
				});
			});

			// declare urls and loop here (loop a second time) to prevent
			// pollution of above closure with unnecessary variables

			var urls = [];

			this.each(function(){
				urls.push($(this).attr('src'));
			});

			var selection = this;

			imgpreload(urls,function(){
				if (settings.all instanceof Function) { settings.all.call(selection); }
			});

			return this;
		};

		// public
		$.fn.imgpreload.defaults =
		{
			each: null // callback invoked when each image in a group loads
			, all: null // callback invoked when when the entire group of images has loaded
		};
	})(jQuery);
}


/*
	contentsHeight = 컨텐츠 높이
	maskHeight = 마스크 높이
	scrollHeight = (contentsHeight 와 maskHeight 로 비율을 계산하고) 비율에 맞게 scrollHeight 값에 따라 scrollBtn 등의 height, 움직일수 있는 Y축 등을 정한다.
	eventTarget = wheel 이벤트를 핸들링할 jQuery 객체(기본은 document).
	wheelMove  = wheel 이벤트시 움직일 percent 비율.

	moveMinY = 움직일 수 있는 Y축의 최소값. (read-only 변경 비권장)
	moveMaxHeight = 움직일 수 있는 Y축의 최대값. (read-only 변경 비권장)
	mouseDownInitY = 마우스로 scrollBtn 다운시 지정되는 Y축 최초값 (read-only 변경 비권장)
	percent = (read-only 변경 절대 비권장) 스크롤바의 위치에 따른 percent값. 최상위는 0 , 최하위는 1. 스크롤바 움직임이 있을시 계속 내부에서 변경되고 담고 있는다.

	setScrollBarHeightRatio() = scrollContainer , scrollBg 등 height 비율 조절
	scrollBtnMoveToVertical() = Y축 이동
	calculatorToPercent() = 비율대비 스크롤바의 위치에 따라 0~1 값 계산
*/
function ScrollBar(initObject){//contentsHeight , maskHeight , scrollHeight, scrollBtn , scrollBg , scrollContainer){
	var _scrollBar = {
		nameSpace: ""
		, contentsHeight: 0
		, maskHeight: 0
		, scrollHeight: 0
		, moveMinY:0
		, moveMaxHeight:0
		, mouseDownInitY:0
		, wheelMove: 10
		, percent:0
		, eventTarget: null
		, isShow:true
		, scrollContainer : null
		, scrollBtn : null
		, scrollBg : null
		, wheelAble : true
	};

	var waitMove = false;

	if(initObject != null){
		(initObject.scrollContainer == null) ? _scrollBar.scrollContainer = $("<div style=\" position:absolute; top:20px; left:20px; width:40px;  background:#ff0000;\">c</div>") : _scrollBar.scrollContainer = initObject.scrollContainer;
		(initObject.scrollBtn == null) ? _scrollBar.scrollBtn = $("<div style=\" position:absolute; top:0px; left:0px; width:40px; background:#333;\">btn</div>") : _scrollBar.scrollBtn = initObject.scrollBtn;
		(initObject.scrollBg == null) ? _scrollBar.scrollBg = $("<div style=\" position:absolute; top:0px; left:0px; width:40px; background:#999;\">bg</div>") : _scrollBar.scrollBg = initObject.scrollBg;
		
		//(initObject.contentsHeight) ? _scrollBar.contentsHeight = initObject.contentsHeight : _scrollBar.contentsHeight = $(window)[0].scrollHeight;
		//(initObject.maskHeight) ? _scrollBar.maskHeight = initObject.maskHeight : _scrollBar.contentsHeight = $(window)[0].scrollHeight;
		//(initObject.scrollHeight) ? _scrollBar.scrollHeight = initObject.scrollHeight : _scrollBar.contentsHeight = $(window)[0].scrollHeight;
		(initObject.contentsHeight) ? _scrollBar.contentsHeight = initObject.contentsHeight : _scrollBar.contentsHeight = _scrollBar.eventTarget[0].scrollHeight;
		(initObject.maskHeight) ? _scrollBar.maskHeight = initObject.maskHeight : _scrollBar.maskHeight = $(window).height();
		(initObject.scrollHeight) ? _scrollBar.scrollHeight = initObject.scrollHeight : _scrollBar.scrollHeight = $(window).height();
		if(initObject.eventTarget) _scrollBar.eventTarget = initObject.eventTarget;
		if(initObject.wheelMove) _scrollBar.wheelMove = initObject.wheelMove;
		if(initObject.nameSpace) _scrollBar.nameSpace = initObject.nameSpace;

		if(initObject.moveMinY) _scrollBar.moveMinY = initObject.moveMinY;
		if(initObject.moveMaxHeight) _scrollBar.moveMaxHeight = initObject.moveMaxHeight;
		if(initObject.mouseDownInitY) _scrollBar.mouseDownInitY = initObject.mouseDownInitY;
	}
	if(_scrollBar.eventTarget == null) _scrollBar.eventTarget = $(document);

	_scrollBar.scrollBtn.css({cursor:"pointer"});
	_scrollBar.scrollContainer.append(_scrollBar.scrollBg);
	_scrollBar.scrollContainer.append(_scrollBar.scrollBtn);

	setScrollBarHeightRatio(_scrollBar.contentsHeight , _scrollBar.maskHeight , _scrollBar.scrollHeight);
	_scrollBar.scrollBtn.mousedown(interactionScrollBtnMouseHandler);
	_scrollBar.scrollBtn.mouseup(interactionScrollBtnMouseHandler);
	_scrollBar.scrollBtn.mouseover(interactionScrollBtnMouseHandler);
	_scrollBar.scrollBtn.mouseout(interactionScrollBtnMouseHandler);
	_scrollBar.eventTarget.mousewheel(interactionScrollBtnMouseHandler);

	function disableDragSelection(){
		document.onselectstart = function(){ return false; }
		document.ondragstart = function(){  return false; }
		document.onmousedown=function(){ return false; }
		document.onkeydown=function(){ return false; }
	}
	function ableDragSelection(){
		document.onselectstart = null;
		document.ondragstart = null;
		document.onmousedown = null;
		document.onkeydown = null;
	}
	
	// Trigger 날리는 mouseEvent
	function interactionScrollBtnMouseHandler(evt , delta){
		if(_scrollBar.isShow == false){
			return;
		}
		var extraParam = {};
		extraParam.nameSpace = _scrollBar.nameSpace;
		switch(evt.type){
			case "mouseover":
				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_OVER , extraParam);
				
				break;

			case "mouseout":
				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_OUT , extraParam);
				break;

			case "mousedown":
				var scrollContainerPosition = _scrollBar.scrollContainer.position();
				var scrollBtnPosition = _scrollBar.scrollBtn.position();
				_scrollBar.mouseDownInitY = evt.pageY - scrollContainerPosition.top - scrollBtnPosition.top;
				$(document).mousemove(interactionScrollBtnMouseHandler);
				$(document).mouseup(unbindScrollMoveEvent);

				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_PRESS , extraParam);

				disableDragSelection();
			
				break;

			case "mouseup":
				unbindScrollMoveEvent();
				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_RELEASE , extraParam);
				break;

			case "mousemove":
				if(waitMove == true){
					waitMove = false;
				}else{
					waitMove = true;
				}
				if(waitMove == false) return;
				
				var scrollContainerPosition = _scrollBar.scrollContainer.position();
				var mouseY =  evt.pageY - scrollContainerPosition.top - _scrollBar.mouseDownInitY;
				scrollBtnMoveToVertical(mouseY);
				calculatorToPercent();
				extraParam.percent = _scrollBar.percent;
				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_DRAG , extraParam);

				break;
				
			case "mousewheel":
				if(_scrollBar.wheelAble == false){
					return;
				}
				var wheelPixelMove = _scrollBar.scrollBtn.position().top - (delta*_scrollBar.wheelMove);
				scrollBtnMoveToVertical(wheelPixelMove);
				calculatorToPercent();

				extraParam.percent = _scrollBar.percent;
				extraParam.delta = delta;
				_scrollBar.eventTarget.trigger(ScrollBar.EVENT_SCROLL_WHEEL , extraParam);
				break;
		}
	};



	//스크롤바의 maskHeight , contentsHeight 를 이용해 percent 값을 계산.
	function calculatorToPercent(){
		var scrollBtnY = _scrollBar.scrollBtn.position().top;
		var scrollBtnH = _scrollBar.scrollBtn.height();
		var scrollContainerH = _scrollBar.scrollContainer.height();
		var percent = scrollBtnY/(scrollContainerH - scrollBtnH);

		if(percent < 0) percent = 0;
		if(percent > 1) percent = 1;
		_scrollBar.percent = percent;
		return percent;
	};



	//컨텐츠 height , 마스크(기준) height 비율로 scrollBtn height를 바꿈.
	function setScrollBarHeightRatio(contentsHeight , maskHeight , scrollHeight){
		_scrollBar.contentsHeight = contentsHeight;
		_scrollBar.maskHeight = maskHeight;
		_scrollBar.scrollHeight = scrollHeight;

		var ratioHeight = scrollHeight;
		if(contentsHeight > maskHeight){
			ratioHeight = Math.floor((maskHeight/contentsHeight)*scrollHeight);
		}
		_scrollBar.scrollContainer.css({height:scrollHeight});
		_scrollBar.scrollBg.css({height:scrollHeight});
		_scrollBar.scrollBtn.css({height:ratioHeight});

		_scrollBar.moveMinY = 0; //_scrollBar.scrollBtn.position().top;
		_scrollBar.moveMaxHeight = _scrollBar.scrollContainer.height() - _scrollBar.scrollBtn.height();
	};



	//스크롤바 Y축 이동.
	function scrollBtnMoveToVertical(positionMouseY){
		var targetMouseY = 0;
		if(_scrollBar.moveMinY < positionMouseY && _scrollBar.moveMaxHeight > positionMouseY){
			targetMouseY = positionMouseY;
		}else if(_scrollBar.moveMinY >= positionMouseY){
			targetMouseY = _scrollBar.moveMinY;
		}else if(_scrollBar.moveMaxHeight <= positionMouseY){
			targetMouseY = _scrollBar.moveMaxHeight;
		}
		_scrollBar.scrollBtn.css({top:(targetMouseY+"px")});
		//_scrollBar.scrollBtn.stop().animate({top:targetMouseY } , { duration:200 , easing:"easeOutExpo"});
	};
	
	_scrollBar.init = function(initObject){
		/*
		if(initObject != null){
			if(initObject.contentsHeight) _scrollBar.contentsHeight = initObject.contentsHeight;
			if(initObject.maskHeight) _scrollBar.maskHeight = initObject.maskHeight;
			if(initObject.scrollHeight) _scrollBar.scrollHeight = initObject.scrollHeight;
			if(initObject.eventTarget) _scrollBar.eventTarget = initObject.eventTarget;
			if(initObject.wheelMove) _scrollBar.wheelMove = initObject.wheelMove;

			if(initObject.moveMinY) _scrollBar.moveMinY = initObject.moveMinY;
			if(initObject.moveMaxHeight) _scrollBar.moveMaxHeight = initObject.moveMaxHeight;
			if(initObject.mouseDownInitY) _scrollBar.mouseDownInitY = initObject.mouseDownInitY;
		}
		if(_scrollBar.eventTarget == null) _scrollBar.eventTarget = $(document);

		setScrollBarHeightRatio(_scrollBar.contentsHeight , _scrollBar.maskHeight , _scrollBar.scrollHeight);
		_scrollBar.scrollBtn.mousedown(interactionScrollBtnMouseHandler);
		_scrollBar.scrollBtn.mouseup(interactionScrollBtnMouseHandler);
		_scrollBar.scrollBtn.mouseover(interactionScrollBtnMouseHandler);
		_scrollBar.scrollBtn.mouseout(interactionScrollBtnMouseHandler);
		_scrollBar.eventTarget.mousewheel(interactionScrollBtnMouseHandler);
		*/
	};

	_scrollBar.getScrollContainer = function(){
		return _scrollBar.scrollContainer;
	};

	//지정된 파라미터의 percent 값에 따라 스크롤바 이동.
	_scrollBar.setPercent = function(targetPercent){
		if(targetPercent < 0) targetPercent = 0;
		if(targetPercent > 1) targetPercent = 1;

		var heightPosition = _scrollBar.scrollContainer.height() - _scrollBar.scrollBtn.height();
		var targetY = ((heightPosition*targetPercent)/heightPosition)*heightPosition;
		
		_scrollBar.percent = targetPercent;
		scrollBtnMoveToVertical(targetY);
	};
	
	//지정된 파라미터의 percent 값에 따라 스크롤바 이동.
	_scrollBar.setPixel = function(targetPixel){
		var maxMoveY = _scrollBar.contentsHeight - _scrollBar.maskHeight;
		if(targetPixel < 0) targetPixel = 0;
		if(targetPixel > maxMoveY) targetPixel = maxMoveY;
		
		var percent = targetPixel/maxMoveY;
		_scrollBar.setPercent(percent);
		/*
		var wheelPixelMove = $(scrollBtn).position().top - (delta*_scrollBar.wheelMove);
		scrollBtnMoveToVertical(wheelPixelMove);
		calculatorToPercent();
		*/
		return percent;
	};



	//스크롤바 resize
	_scrollBar.resize = function(contentsHeight , maskHeight , scrollHeight){
		var tempScrollHeight = _scrollBar.scrollHeight;
		var tempPercent = _scrollBar.percent;
		setScrollBarHeightRatio(contentsHeight , maskHeight , scrollHeight);

		//스크롤바를 resize 할 때 기존 scrollHeight 보다 커질 경우 변경된 비율에서의 percent 값의 위치로 유지하게 한다.
		_scrollBar.setPercent(tempPercent);
	};

	_scrollBar.show = function(){
//		_scrollBar.scrollContainer.css({opacity:1});
		_scrollBar.scrollContainer.css({visibility : "visible"}); 
		
		_scrollBar.isShow = true;
	}
	_scrollBar.hide = function(){
//		_scrollBar.scrollContainer.css({opacity:0});
		_scrollBar.scrollContainer.css({visibility : "hidden"});
		_scrollBar.isShow = false;
	}


	// mouseEvent 해지
	function unbindScrollMoveEvent(){
		$(document).unbind( "mouseup" , unbindScrollMoveEvent);
		$(document).unbind( "mousemove" , interactionScrollBtnMouseHandler);
		ableDragSelection();
	};

	return _scrollBar;
}
ScrollBar.EVENT_SCROLL_OVER    = "EVENT_SCROLL_OVER";
ScrollBar.EVENT_SCROLL_OUT     = "EVENT_SCROLL_OUT";
ScrollBar.EVENT_SCROLL_PRESS     = "EVENT_SCROLL_PRESS";
ScrollBar.EVENT_SCROLL_RELEASE = "EVENT_SCROLL_RELEASE";
ScrollBar.EVENT_SCROLL_DRAG      = "EVENT_SCROLL_DRAG";
ScrollBar.EVENT_SCROLL_WHEEL    = "EVENT_SCROLL_WHEEL";


/**
 * ScrollContent
 */
function ScrollContent(scrollContentOption){
	scrollContentOption = scrollContentOption || {};
	var $scrollContentContainer = null;
	var $scrollContentTarget = null;
	var contentsHeightData = null;
	var contentsSpaceHeight = null;
	var scrollBarHeight = null;
		
	function pixelToPercentage(pixelValue)
	{
		return pixelValue / (contentsHeightData.contentsHeight - contentsHeightData.maskHeight);
	}
	
	this.scrollBar = null;
	
	this.getContentHeightData = function()
	{
		var maskHeight = (scrollContentOption.contentH ) ? scrollContentOption.contentH : $scrollContentContainer.height();
		
		if(contentsSpaceHeight != null){
			maskHeight = maskHeight - contentsSpaceHeight;
		}
		
		
		return {
			maskHeight : maskHeight 
			,contentsHeight : $scrollContentContainer[0].scrollHeight
		}
	};
	
	this.contentHeightUpDate = function()
	{
		if(typeof contentsHeightData == 'undefined') return false;
		contentsHeightData = this.getContentHeightData();
	};
	
	this.moveToPixel = function(movePixelValue)
	{
		movePixelValue = (typeof movePixelValue != 'undefined') ? movePixelValue : 0;
		var percentageValue = pixelToPercentage(movePixelValue);
		this.scrollMoveToPercentage(percentageValue);
	};
	
	this.scrollMoveToPercentage = function(percentage)
	{
		var contentTop = (contentsHeightData.contentsHeight - contentsHeightData.maskHeight) * percentage;
		
		if($scrollContentTarget != null){
			$scrollContentTarget.stop().animate({
				top : -contentTop
			}, { duration:400 , easing:"easeOutExpo"})	
		}else{
			$scrollContentContainer.stop().animate({
				scrollTop : contentTop
			}, { duration:400 , easing:"easeOutExpo"})
		}
	}
	
	this.resize = function(o)
	{
		contentsHeightData.maskHeight = o.contentH || contentsHeightData.maskHeight;
		contentsHeightData.contentsHeight = o.contentInnerH || contentsHeightData.contentsHeight;   
		
		var cH = contentsHeightData.contentsHeight;
		var mH = contentsHeightData.maskHeight;
		
//		(cH > mH) ? (this.show()) : (this.hide());
		if(cH > mH){
			this.show();
		}else{
			this.hide();
		}

		this.scrollBar.resize(cH, mH, scrollBarHeight);
		this.scrollMoveToPercentage(this.scrollBar.percent);
	};
	
	this.hide = function()
	{
		this.scrollBar.hide();
	};
	
	this.show = function()
	{
		this.scrollBar.show();
	};
	
	this.init = function(nameSpace, scrollContentContainer)
	{
		$scrollContentContainer = scrollContentContainer.eventTarget;
		$scrollContentTarget = (scrollContentContainer.scrollTarget) ? scrollContentContainer.scrollTarget : null; 
		
		contentsSpaceHeight = (scrollContentContainer.scrollTargetSpace) ? scrollContentContainer.scrollTargetSpace : 0;
		
		this.contentHeightUpDate();
		
		scrollBarHeight = (scrollContentContainer.scrollHeight) ? scrollContentContainer.scrollHeight : contentsHeightData.maskHeight;
		
		scrollContentContainer.nameSpace = nameSpace;
		scrollContentContainer.maskHeight = contentsHeightData.maskHeight;
//		scrollContentContainer.scrollTargetSpace = contentsSpaceHeight;
		scrollContentContainer.contentsHeight = contentsHeightData.contentsHeight;
		scrollContentContainer.scrollHeight = scrollBarHeight

		this.scrollBar = new ScrollBar(scrollContentContainer);
	};
}

// jQuery Mouse Right Click False
if(jQuery) (function(){$.extend($.fn, {rightClick: function(handler) {$(this).each( function() {$(this).mousedown( function(e) {var evt = e;$(this).mouseup( function() {$(this).unbind('mouseup');if( evt.button == 2 ) {handler.call( $(this), evt );return false;} else {return true;}});});$(this)[0].oncontextmenu = function() {return false;}});return $(this);},rightMouseDown: function(handler) {$(this).each( function() {$(this).mousedown( function(e) {if( e.button == 2 ) {handler.call( $(this), e );return false;} else {return true;}});$(this)[0].oncontextmenu = function() {return false;}});return $(this);},rightMouseUp: function(handler) {$(this).each( function() {$(this).mouseup( function(e) {if( e.button == 2 ) {handler.call( $(this), e );return false;} else {return true;}});$(this)[0].oncontextmenu = function() {return false;}});return $(this);},noContext: function() {$(this).each( function() {$(this)[0].oncontextmenu = function() {return false;}});return $(this);}});})(jQuery);
