/*
Require /n/common.js
*/

/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var Easing = {
    easeNone: function (t, b, c, d) { return c*t/d + b; },
    easeIn: function (t, b, c, d) { return c*(t/=d)*t + b; },
    easeOut: function (t, b, c, d) { return -c *(t/=d)*(t-2) + b; },
    easeBoth: function (t, b, c, d) {
    	if ((t/=d/2) < 1) return c/2*t*t + b;
    	return -c/2 * ((--t)*(t-2) - 1) + b; },
    easeInStrong: function (t, b, c, d) { return c*(t/=d)*t*t*t + b; },
    easeOutStrong: function (t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; },
    easeBothStrong: function (t, b, c, d) {
    	if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
    	return -c/2 * ((t-=2)*t*t*t - 2) + b; },
    elasticIn: function (t, b, c, d, a, p) {
    	if (t == 0) return b;
        if ( (t /= d) == 1 ) return b+c;
        if (!p) p=d*.3;
    	if (!a || a < Math.abs(c)) { a = c; var s = p/4; }
    	else var s = p/(2*Math.PI) * Math.asin (c/a);
    	return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; },
    elasticOut: function (t, b, c, d, a, p) {
    	if (t == 0) return b;
        if ( (t /= d) == 1 ) return b+c;
        if (!p) p=d*.3;
    	if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
    	else var s = p/(2*Math.PI) * Math.asin (c/a);
    	return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; },
    elasticBoth: function (t, b, c, d, a, p) {
    	if (t == 0) return b;
        if ( (t /= d/2) == 2 ) return b+c;
        if (!p) p = d*(.3*1.5);
    	if ( !a || a < Math.abs(c) ) { a = c; var s = p/4; }
    	else var s = p/(2*Math.PI) * Math.asin (c/a);
    	if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    	return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; },
    backIn: function (t, b, c, d, s) {
    	if (typeof s == 'undefined') s = 1.70158;
    	return c*(t/=d)*t*((s+1)*t - s) + b; },
    backOut: function (t, b, c, d, s) {
    	if (typeof s == 'undefined') s = 1.70158;
    	return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; },
    backBoth: function (t, b, c, d, s) {
    	if (typeof s == 'undefined') s = 1.70158; 
    	if ((t /= d/2 ) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; },
    bounceIn: function (t, b, c, d) { return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; },
    bounceOut: function (t, b, c, d) {
    	if ((t/=d) < (1/2.75)) return c*(7.5625*t*t) + b;
    	else if (t < (2/2.75)) return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    	else if (t < (2.5/2.75)) return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; },
    bounceBoth: function (t, b, c, d) {
    	if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b;
    	return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; }
};

var Anim = function(elm, attrs, duration, method) {
	this.init(elm, attrs, duration, method);
}

Anim.prototype = {
	init: function(elm, attrs, duration, method) {
		this.elm = elm;
		this.duration = duration || 1000;
		this.method = method || Easing.easeNone;
		this.attribute = attrs || {};
		
		this.currentFrame = 0;
		this.totalFrames = MotionMgr.fps;
		this.useSeconds = true;
		
		this._startTime = null;
		this._isAnimated = false;
	
		// { width : { to : deltaW }, height: { to : deltaH } }
		var iw=parseInt(domHelper.getComputedStyle(elm,'width'));
		var ih=parseInt(domHelper.getComputedStyle(elm,'height'));
		var tw=iw,th=ih;
		
		if (typeof attrs.width !== 'undefined' && typeof attrs.width.to !== 'undefined') tw=attrs.width.to;
		if (typeof attrs.height !== 'undefined' && typeof attrs.height.to !== 'undefined') th=attrs.height.to;
		
		this.start = [iw, ih];
		this.end = [tw, th];
		
		var onStart=function() {
			this.onStart.fire();
			this._isAnimated = true;
			this._startTime = new Date();
		};
		
		var onTween=function() {
			var wh = this.doMethod(this.start, this.end);
			this.elm.style.width = parseInt(wh[0]) + 'px';
			this.elm.style.height = parseInt(wh[1]) + 'px';
		};
		
		var onComplete=function() {
			this._isAnimated = false;
			this.onComplete.fire();
		};
		
		this.onStart = new domHelper.customEvent('start', this);
		this._onStart = new domHelper.customEvent('_start', this);
		
		this._onTween = new domHelper.customEvent('_tween', this);
		
		this.onComplete = new domHelper.customEvent('complete', this);
		this._onComplete = new domHelper.customEvent('_complete', this);
		
		this._onStart.subscribe(onStart);
		this._onTween.subscribe(onTween);
		this._onComplete.subscribe(onComplete);
	},
	animate : function() {
		if (this._isAnimated) return false;
		MotionMgr.addMotion(this);
	},
	isAnimated : function() {
		return this._isAnimated;
	},
	getStartTime : function() {
		return this._startTime;
	},
	doMethod : function(start, end) {
		return [this.method(this.currentFrame, start[0], end[0]-start[0], this.totalFrames),
			this.method(this.currentFrame, start[1], end[1]-start[1], this.totalFrames)];
	}
}

var Motion = function(elm, attrs, duration, method) {
	this.init(elm, attrs, duration, method);
}

Motion.prototype = {
	init : function(elm, attrs, duration, method) {
		this.elm = elm;
		this.duration = duration || 1000;
		this.method = method || Easing.easeNone;
		this.attribute = attrs || {};
		
		this.currentFrame = 0;
		this.totalFrames = MotionMgr.fps;
		this.useSeconds = true;
		
		this._startTime = null;
		this._isAnimated = false;
		
		// {points: {by: [deltaX, deltaY]}} 형식만 지원
		var offset = attrs.points.by;
		this.start = [parseInt(elm.style.left), parseInt(elm.style.top)];
		this.end = [this.start[0] + offset[0], this.start[1] + offset[1]];
		
		var onStart=function() {
			this.onStart.fire();
			this._isAnimated = true;
			this._startTime = new Date();
		};
		var onTween=function() {
			var pt = this.doMethod(this.start, this.end);
			this.elm.style.left = parseInt(pt[0]) + 'px';
			this.elm.style.top = parseInt(pt[1]) + 'px';
		};
		var onComplete=function() {
			this._isAnimated = false;
			this.onComplete.fire();
		};
				
		this.onStart = new domHelper.customEvent('start', this);
		this._onStart = new domHelper.customEvent('_start', this);
		
		this._onTween = new domHelper.customEvent('_tween', this);
		
		this.onComplete = new domHelper.customEvent('complete', this);
		this._onComplete = new domHelper.customEvent('_complete', this);
		
		this._onStart.subscribe(onStart);
		this._onTween.subscribe(onTween);
		this._onComplete.subscribe(onComplete);
	},

	animate : function() {
		if (this._isAnimated) return false;
		MotionMgr.addMotion(this);
	},
	isAnimated : function() {
		return this._isAnimated;
	},
	getStartTime : function() {
		return this._startTime;
	},
	doMethod : function(start, end) {
		return [this.method(this.currentFrame, start[0], end[0]-start[0], this.totalFrames),
			this.method(this.currentFrame, start[1], end[1]-start[1], this.totalFrames)];
	}
}

var MotionMgr = new function() {
	this.delay = 1;
	this.fps = 1000;
	var queue = [];
	var thread = null;
	this.addMotion = function(tween) {
		queue[queue.length] = tween;
		tween._onStart.fire();
		this.start();
	};
	this.removeMotion = function(tween, i) {
		i = i || getIndex(tween);
		if (i === -1) return false;
		
		tween._onComplete.fire();
		queue.splice(i, 1);
		
		if (queue.length == 0) this.stop();
		return true;
	};
	this.start = function() {
		if (thread === null)
			thread = window.setInterval(this.run, this.delay);
	};
	this.stop = function(tween) {
		if (tween)
			MotionMgr.removeMotion(tween);
		else {
			window.clearInterval(thread);
			for (var i = 0; i < queue.length; i++) this.removeMotion(queue[0], 0);
			queue = [];
			thread = null;
		}
	};
	this.run = function(e) {
		for (var i = 0; i < queue.length; i++) {
			var t = queue[i];
			if (t.currentFrame < t.totalFrames || t.totalFrames === null) {
				t.currentFrame++;
				if (t.useSeconds) correctFrame(t);
				t._onTween.fire();
			} else
				MotionMgr.stop(t);
		}
	};
	var getIndex = function(t) {
		for (var i = 0; i < queue.length; i++) {
			if (queue[i] == t) return i;
		}
		return -1;
	};
	var correctFrame = function(tween) {
		var frames = tween.totalFrames;
        var frame = tween.currentFrame;
        var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
        var elapsed = (new Date() - tween.getStartTime());
        var tweak = 0;
        if (elapsed < tween.duration * 1000) tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
        else tweak = frames - (frame + 1); 
        if (tweak > 0 && isFinite(tweak)) {
            if (tween.currentFrame + tweak >= frames) tweak = frames - (frame + 1);
            tween.currentFrame += tweak;      
        }
	};
}

// options
//   className : item clasname, default:box_item
//   container : box container element id, default:parent node
//   slideWidth : visible slide width, default:container width
//   leftButton : left sliding button element id, default:slideLeft
//   rightButton : left sliding button element id, default:slideRight
var SlidingBox = function(box, options) {
	
	options = options || {};
	
	this.box = box;
	this.boxEl = document.getElementById(box);
	
	this.boxEl.style.position = 'absolute';
	this.boxEl.style.left = '0';
	this.boxEl.style.top = '0';
	
	this.className = options.className || 'box_item';
	this.container = document.getElementById(options.container) || this.boxEl.parentNode;
	var items = domHelper.getElementsByClassName(this.boxEl, this.className);
	this.itemWidth = items[0].offsetWidth; // margin은 고려안됨
	this.maxWidth = 0;
	var selected = -1; // 선택된놈
	for (var i = 0; i < items.length; i++) {
		this.maxWidth += items[i].offsetWidth;
		if (domHelper.cssjs('check', items[i], 'selected')) selected = i;
	}
	this.boxEl.style.width = this.maxWidth + 'px';
	
	this.movedBy = 0;
	this.containerSize = Math.floor(this.container.offsetWidth / this.itemWidth); // 영역 내 출력 개수
	this.slideWidth = options.slideWidth || this.containerSize; // 한번에 스라이딩되는 개수
	
	// selected
	if (selected > 0) {
		var n = parseInt(selected / this.slideWidth);
		this.boxEl.style.left = -n * this.slideWidth * this.itemWidth + 'px'; //this.slideBy();
		this.movedBy += n * this.slideWidth * this.itemWidth;
	}
	
	// event registration
	var left = options.leftButton ? document.getElementById(options.leftButton) : document.getElementById('slideLeft'); 
	var right = options.rightButton ? document.getElementById(options.rightButton) : document.getElementById('slideRight');
	if (left && right) {
		domHelper.addEvent(left, 'click', function(e) {
			if (this.anim && this.anim.isAnimated()) {
				domHelper.cancelClick(e);
				return;
			}
			if (!this.slideLeft()) {
				domHelper.cssjs('add', left, 'off');
				left.setAttribute('disabled', 'disabled');
			}
			domHelper.cssjs('remove', right, 'off');
			right.removeAttribute('disabled');
			domHelper.cancelClick(e);
		}, false, null, this);
		domHelper.addEvent(right, 'click', function(e) {
			if (this.anim && this.anim.isAnimated()) {
				domHelper.cancelClick(e);
				return;
			}
			if (!this.slideRight()) {
				domHelper.cssjs('add', right, 'off');
				right.setAttribute('disabled', 'disabled');
			}
			domHelper.cssjs('remove', left, 'off');
			left.removeAttribute('disabled');
			domHelper.cancelClick(e);
		}, false, null, this);
	}
	
	// button initialize
	if (this.movedBy >= this.slideWidth * this.itemWidth) {
		domHelper.cssjs('remove', left, 'off');
		left.removeAttribute('disabled');
	} else {
		domHelper.cssjs('add', left, 'off');
		left.setAttribute('disabled', 'disabled');
	}
	if (this.movedBy < this.maxWidth - this.slideWidth * this.itemWidth) {
		domHelper.cssjs('remove', right, 'off');
		right.removeAttribute('disabled');
	} else {
		domHelper.cssjs('add', right, 'off');
		right.setAttribute('disabled', 'disabled');
	}
}
SlidingBox.prototype = {
	slideBy: function(delta) {
		this.anim = new Motion(this.boxEl, {points: {by: [delta, 0]}}, 0.5, Easing.easeBoth);
		this.anim.animate();
	},
	slideLeft : function() {
		if (this.movedBy >= this.slideWidth * this.itemWidth) {
			this.slideBy(this.slideWidth * this.itemWidth);
			this.movedBy -= this.slideWidth * this.itemWidth;
		}
		return (this.movedBy >= this.slideWidth * this.itemWidth);
	},
	slideRight : function() {
		if (this.movedBy < this.maxWidth - this.slideWidth * this.itemWidth) {
			this.slideBy(-this.slideWidth * this.itemWidth);
			this.movedBy += this.slideWidth * this.itemWidth;
		}
		return (this.movedBy < this.maxWidth - this.slideWidth * this.itemWidth);
	}
}
