MooTools.lang.set('ko-KR', 'Form.Validator', {
	required:'이 항목은 반드시 입력해야 합니다.',
	minLength:'최소 {minLength}자 이상 입력해야 합니다. (현재 {length} 자)',
	'maxLength':'최대 {maxLength}자 입력할 수 있습니다. (현재 {length} 자).',
	integer:'이 항목에는 숫자만 입력해야 합니다.',
	numeric:'Please enter only numeric values in this field (i.e. "1" or "1.1" or "-1" or "-1.1").',
	digits:'숫자와 "-", "," 만 입력할 수 있습니다.',
	alpha:'Please use letters only (a-z) with in this field. No spaces or other characters are allowed.',
	alphanum:'영문과 숫자만 입력가능합니다.',
	dateSuchAs:'Please enter a valid date such as {date}',
	dateInFormatMDY:'Please enter a valid date such as MM/DD/YYYY (i.e. "12/31/1999")',
	email:'이메일 형식에 맞기 않습니다. (예. abc@company.com)',
	url:'URL 형식이 아닙니다. (예. http://www.abc.com)',
	currencyDollar:'Please enter a valid $ amount. For example $100.00 .',
	oneRequired:'Please enter something for at least one of these inputs.',
	errorPrefix: '에러: ',
	warningPrefix: 'Warning: ',
	noSpace: '입력값에 공백이 포함되면 안됩니다.',
	reqChkByNode: 'No items are selected.',
	requiredChk: 'This field is required.',
	reqChkByName: 'Please select a {label}.',
	'match': '이 항목은 &quot;{matchName}&quot; 항목과 일치해야 합니다.',
	startDate: 'the start date',
	endDate: 'the end date',
	currendDate: 'the current date',
	afterDate: 'The date should be the same or after {label}.',
	beforeDate: 'The date should be the same or before {label}.',
	startMonth: 'Please select a start month',
	sameMonth: 'These two dates must be in the same month - you must change one or the other.'
});

MooTools.lang.set('ko-KR', 'Date', {
	months: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	days: ['일', '월', '화', '수', '목', '금', '토'],
	dateOrder: ['일', '월', '년', '-']
});

var fancy_upload_strings = {
	'fileName': '{name}',
	'cancel': 'Cancel',
	'cancelTitle': 'Click to cancel and remove this entry.',
	'validationErrors': {
		'duplicate': 'File <em>{name}</em> is already added, duplicates are not allowed.',
		'sizeLimitMin': 'File <em>{name}</em> (<em>{size}</em>) is too small, the minimal file size is {fileSizeMin}.',
		'sizeLimitMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, the maximal file size is <em>{fileSizeMax}</em>.',
		'fileListMax': 'File <em>{name}</em> could not be added, amount of <em>{fileListMax} files</em> exceeded.',
		'fileListSizeMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, overall filesize of <em>{fileListSizeMax}</em> exceeded.'
	},
	'errors': {
		'httpStatus': 'Server returned HTTP-Status #{code}',
		'securityError': 'Security error occured ({text})',
		'ioError': 'Error caused a send or load operation to fail ({text})'
	},
	'linuxWarning': 'Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nDo you want to start the upload anyway?'
};

MooTools.lang.set('ko-KR', 'FancyUpload', fancy_upload_strings);

MooTools.lang.setLanguage('ko-KR');
var Logger = new Log;
//Logger.enableLog();

Form.Validator.addAllThese([
	['validate-match', {
		errorMsg: function(element, props){
			return Form.Validator.getMsg('match').substitute({matchName: props.matchName || document.id(props.matchInput).get('name')});
		},
		test: function(element, props){
			var eleVal = element.get('value');
			var matchVal = document.id(props.matchInput) && document.id(props.matchInput).get('value');
			return eleVal == matchVal;
		}
	}]
]);

Clientcide.setAssetLocation('/resource/script/clientcide/assets');

if (!$type(artpq)) var artpq = {};

artpq.ImageButton = new Class({
	Implements: [Events, Options],
	options: {
		overSuffix: '_r',
		out: true,
		container: null,
		layers: [],
		target: null,
		selectClassName: 'ibSelected',
		defaultClassName: 'ibDefault',
		overClassName: 'artpqRotatorSelected',
		fade: true,
		displayView: 'block',
		prebuild: true,
		supportKeyboard: true
	},

	initialize: function(elements, options){
		this.setOptions(options);
		this.selected = -1;
		this.defaultSelect = -1;
		this.lBound = elements[0].getPosition().x;
		this.rBound = elements[elements.length - 1].getPosition().x + elements[elements.length - 1].getSize().x;
		this.imageElements = elements;
		if (this.options.prebuild) this.build();
		return this;
	},

	getOverSource: function(img) {
		return img.get('src').replace(RegExp("(\.[^\.]+)$"), this.options.overSuffix + "$1");
	},

	build: function(){

		this.elements = [];

		for (var i  = 0, n = this.imageElements.length; i < n; i++){

			var sourceImage = $(this.imageElements[i]);
			var source = sourceImage.getProperty('src');
			var overSource = this.getOverSource(sourceImage);
			var layer = ($defined(this.options.layers[i]) ? this.options.layers[i] : null);

			if ($defined(this.options.target)) source = $(this.options.target).getProperty('src');
			if ($defined(layer)) {
				if (this.options.fade) {
					layer.setStyle('opacity', 0);
					layer.setStyle('display', this.options.displayView);
				} else {
					layer.setStyle('display', 'none');
				}
			}

			sourceImage.addEvent('mouseenter', this.onMouseOver.bindWithEvent(this, i));
			if (this.options.supportKeyboard) sourceImage.getParent().addEvent('focus', this.onMouseOver.bindWithEvent(this, i));
			if(this.options.out) {
				sourceImage.addEvent('mouseleave', this.onMouseLeave.bindWithEvent(this, i));
				if (this.options.supportKeyboard) sourceImage.getParent().addEvent('blur', this.onMouseLeave.bindWithEvent(this, i));
			}

			this.elements[i] = {
				image: sourceImage,
				source: source,
				overSource: overSource,
				layer: layer
			};

			if (sourceImage.hasClass(this.options.selectClassName) || sourceImage.hasClass(this.options.defaultClassName)){

				sourceImage.setProperty('src', overSource);
				this.selectedIndex = i;
				if ($chk(layer)) this.select(i);

				if (sourceImage.hasClass(this.options.defaultClassName) && $defined(this.options.container)){
					this.defaultSelect = i;
					Logger.log(' set default : ' + this.defaultSelect);
					$(this.options.container).addEvent('mouseleave', (function(evt){
						this.unSelect(this.selected);
						this.onMouseOver(evt, this.defaultSelect);
					}).bindWithEvent(this) );
				}
			}
		}

		if ($defined(this.options.container)) {
			$(this.options.container).addEvent('mouseleave', (function(evt){
				this.fireEvent('leaveContainer', new Event(evt));
			}).bindWithEvent(this));
		}


	},

	select: function(index){
		var el = this.elements[index];
		this.unSelect(index);
		if($defined(this.options.target)) $(this.options.target).set('src', el.overSource);
		else el.image.set('src', el.overSource);
		if ($defined(el.layer)) {
			el.layer.setStyle('display', this.options.displayView);
			if (this.options.fade) el.layer.fade('in');
		}
		el.image.addClass(this.options.overClassName);
		this.selectedIndex = index;
		this.fireEvent('onSelect', index);
	},

	onMouseOver: function(evt, index){
		this.select(index);
		this.fireEvent('onMouseOver', [new Event(evt), index]);
	},

	unSelect: function(currentIndex){
		if (this.selectedIndex > -1 && this.selectedIndex != currentIndex) {
			var el = this.elements[this.selectedIndex];

			if($defined(this.options.target)) $(this.options.target).setProperty('src', el.source);
			else el.image.setProperty('src', el.source);
			if ($defined(el.layer)) {
				if (this.options.fade) el.layer.fade('out');
				el.layer.setStyle('display', 'none');
			}
			el.image.removeClass(this.options.overClassName);
			this.selectedIndex = -1;
			if (currentIndex > -1) this.fireEvent('onUnSelect', currentIndex);
		}
	},

	onMouseLeave: function(evt, index){
		this.unSelect(-1);
		this.fireEvent('onMouseOut', [new Event(evt), index]);
	}
});

artpq.ImageButtonProperty = new Class({
	Extends: artpq.ImageButton,
	getOverSource: function(img) {
		return img.get('over');
	}
});

artpq.ImageButtonClass = new Class({
	Extends: artpq.ImageButton,
	getOverSource: function(img) {
		var classes = img.get('class').split(' ');
		for (var i = 0; i < classes.length; i++) {
			var values = classes[i].split(':');
			if (values.length > 1) {
				if (values[0] == 'over') return values[1];
			}
		}
		return '';
	}
});

Fx.Scroll2 = new Class({
	'Extends': Fx.Scroll,
	'styleString': Element.getComputedStyle,
	'styleNumber': function(element, style) {return this.styleString(element, style).toInt() || 0;},
	'borderBox': function(element) {return this.styleString(element, '-moz-box-sizing') == 'border-box';},
	'topBorder': function(element) {return this.styleNumber(element, 'border-top-width');},
	'leftBorder': function(element) {return this.styleNumber(element, 'border-left-width');},
	'isBody': function(element) {return (/^(?:body|html)$/i).test(element.tagName);},
	'toElement': function(el) {
		var offset   = {x: 0, y: 0};
		var element  = $(el);

		if (this.isBody(element)) {return offset;}
		var scroll = element.getScrolls();

		while (element && !this.isBody(element)){
			offset.x += element.offsetLeft;
			offset.y += element.offsetTop;

			if (Browser.Engine.gecko){
			if (!this.borderBox(element)){offset.x += this.leftBorder(element);offset.y += this.topBorder(element);}
			var parent = element.parentNode;
			if (parent && this.styleString(parent, 'overflow') != 'visible'){offset.x += this.leftBorder(parent);offset.y += this.topBorder(parent);}
			} else if (Browser.Engine.trident || Browser.Engine.webkit){offset.x += this.leftBorder(element);offset.y += this.topBorder(element);}
			element = element.offsetParent;
			if (Browser.Engine.trident) {while (element && !element.currentStyle.hasLayout) {element = element.offsetParent;}}
		}

		if (Browser.Engine.gecko && !this.borderBox(element)){
			offset.x -= this.leftBorder(element);
			offset.y -= this.topBorder(element);
		}

		var relative = this.element;
		var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};
		var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
		return this.start(position.x - relativePosition.x, position.y - relativePosition.y);
	}
});

artpq.Rotator = new Class({
	Implements: [Events, Options],

	options: {
		interval: 4000,
		ibOptions: {
			selectClassName: 'artpqRotatorSelected',
			out: false
		},
		fx: {
			wait: false,
			duration: 800,
			transition: Fx.Transitions.Sine.easeIn
		},
		mouseTriggerPanel: false
	},

	initialize: function(container, triggers, layers, options) {
		this.setOptions(options);
		this.container = $(container);
		this.triggers = triggers;
		this.layers = layers;
		this.current = 0;
		this.timer = null;

		this.buildTriggers();

		this.triggerPanel = null;
		if (this.options.mouseTriggerPanel) this.triggerPanel = $(this.options.mouseTriggerPanel);
		this.buildLayers();

		this.scroller = new Fx.Scroll(this.container, this.options.fx);
		this.imageButton = new artpq.ImageButton(this.triggers, this.options.ibOptions);

		this.addImageButtonEvents();

		return this;
	},

	addImageButtonEvents: function() {
		var thisObj = this;
		this.imageButton.addEvent('onMouseOver', function(evt, index){
			thisObj.stop();
			thisObj.scroller.toElement( thisObj.layers[ index ] );
			thisObj.current = index;
		});

		this.imageButton.addEvent('onMouseOut', function(evt, index){
			thisObj.play();
		});
	},

	buildTriggers: function() {
		this.triggers.each(function(trigger, i) {
			if (i == 0) trigger.addClass('artpqRotatorSelected');
		});
	},

	buildLayers: function() {
		var table = new Element('table', {
			border:'0', cellpadding:'0', cellspacing:'0','class': 'rotatorInnerTable',
			'styles': {
				borderCollapse: 'collapse',
				tableLayout: 'auto'
			}
		});
		this.layers.each(function(layer) {
			if (table.rows.length == 0) table.insertRow(0);
			var row = table.rows[0];
			var newCell = row.insertCell(row.cells.length);
			newCell.appendChild(layer);
		}, this);
		this.table = table;
		this.table.inject( this.container );

		if (this.triggerPanel) {
			this.triggerPanel.setStyle('cursor', 'pointer');
			this.triggerPanel.addEvent('mouseenter', this.stop.bind(this));
			this.triggerPanel.addEvent('mouseleave', this.play.bind(this));
			//this.addLinkToContainer(0);
		} else {
			this.table.addEvent('mouseenter', this.stop.bind(this));
			this.table.addEvent('mouseleave', this.play.bind(this));
		}
	},

	play: function(){

		this.timer = this.go.periodical(this.options.interval, this);
	},

	stop: function() {

		if ($defined(this.timer)) {
			$clear(this.timer);
			this.timer = null;
		}
	},

	go: function() {
		this.current++;
		if (this.current >= this.triggers.length) this.current = 0;
		this.imageButton.select(this.current);
		//this.addLinkToContainer(this.current);
		this.scroller.toElement(this.layers[this.current]);
	}
//
//	addLinkToContainer: function(current) {
//		var c = $pick(current,0);
//		if (this.triggerPanel && this.layers[c].getFirst('a').get('tag') == 'a') {
//			var a = this.layers[c].getFirst('a');
//			this.triggerPanel.removeEvents('click');
//			if (a.get('target')) {
//				this.triggerPanel.addEvent('click', function() { window.open(a.get('href')); });
//			} else {
//
//				this.triggerPanel.addEvent('click', function() { location.href = a.get('href'); });
//			}
//		}
//	}

});

artpq.Floater = new Class({
	Extends: Fx.Tween,

	options: {
		fps: 80,
		link: 'cancel',
		bottom: null,
		container: null
	},
	initialize: function(floater, options){
		this.setOptions(options);
		this.options = $merge(this.options, {property: 'top'});
		this.parent($(floater), this.options);
		this.initTop = this.element.getPosition($(this.options.container)).y;
		this.isPlay = true;
		this.set(this.initTop);
		this.prevTop = this.initTop;

		this.bottomBound = 999999999;
		if (this.options.bottom) this.bottomBound = $(this.options.bottom).getPosition().y - this.element.getSize().y;
		if (this.options.container) {
			this.bottomBound = $(this.options.container).getSize().y - this.element.getSize().y;
		}
		window.addEvent('scroll', this.adjustTop.bindWithEvent(this));
	},

	adjustTop: function(){
		if (this.isPlay) {
			var newTop = this.computeTop();
			newTop = Math.max(newTop, this.initTop);
			newTop = Math.min(newTop, this.bottomBound);

			if (this.prevTop != newTop) {
				this.start(newTop);
				this.prevTop = newTop;
			}
		}
	},

	computeTop: function(){
		return $(window).getScroll().y + this.initTop;
	},

	fix: function(){
		this.set(this.initTop);
		this.prevTop = this.initTop;
		this.isPlay = false;
	},

	play: function(){
		this.isPlay = true;
		this.adjustTop();
	}
});

artpq.Floater.KeepTop = new Class({
	Extends: artpq.Floater,
	computeTop: function(){
		if ($defined(this.options.container)) {
			return $(window).getScroll().y - $(this.options.container).getPosition().y;
		} else {
			return $(window).getScroll().y;
		}
	}
});

artpq.NewsTicker = new Class({
	Implements: [Events, Options, Log],
	options: {
		wait: 2000,
		duration: 800,
		link: 'chain',
		onComplete: this.onComplte,
		playButton: null,
		pauseButton: null,
		prevButton: null,
		nextButton: null
	},
	initialize: function(el, options) {
		this.setOptions(options);
		if (this.options.log) this.enableLog();
		this.el = el;
		this.fx = new Fx.Tween(this.el, {
			property: 'top',
			duration: this.options.duration,
			onComplete: this.complete.bind(this)
		});
		this.items = this.el.getElements('li');
		this.timer = null;
		this.current = 0;
		this.playing = false;
		this.down = true;

		if (this.options.playButton) {
			this.options.playButton.addEvent('click', this.play.bindWithEvent(this));
		}
		if (this.options.pauseButton) {
			this.options.pauseButton.addEvent('click', this.pause.bindWithEvent(this));
		}
		if (this.options.nextButton) {
			this.options.nextButton.addEvent('click', (function(evt) {
				this.pause();
				this.next();
			}).bindWithEvent(this));
		}
		if (this.options.prevButton) {
			this.options.prevButton.addEvent('click', (function(evt) {
				this.pause();
				this.prev();
			}).bindWithEvent(this));
		}
	},

	complete: function() {
		this.log('complete: ' + this.current);
		if (this.down) {
			var i = (this.current==0)?this.items.length:this.current;
			this.items[i-1].inject(this.el, 'bottom');
			this.el.setStyles({'top':0});
		}
	},
	isPlay: function() {
		return this.playing;
	},
	play: function() {
		if (this.timer == null) {
			this.log('play');
			this.playing = true;
			var fn = function(){ this.next(); };
			this.timer = fn.periodical(this.options.wait + this.options.duration, this);

			if (this.options.playButton) this.options.playButton.hide();
			if (this.options.pauseButton) this.options.pauseButton.show('inline');
		}
	},
	pause: function() {
		if (this.timer != null) {
			this.log('pause');
			this.playing = false;
			$clear(this.timer);
			this.timer = null;

			if (this.options.pauseButton) this.options.pauseButton.hide();
			if (this.options.playButton) this.options.playButton.show('inline');
		}
	},
	next: function() {
		this.current++;
		this.log('next : ' + this.current);
		if (this.current >= this.items.length) this.current = 0;
		var pos = this.items[this.current].getPosition(this.el);
		this.down = true;
		this.fx.start(-pos.y);
	},
	prev: function() {
		var i = (this.current==0)?this.items.length:this.current;
		this.items[i-1].inject(this.el, 'top' );
		this.el.setStyle('top', -this.items[this.current].getHeight());
		this.current--;
		if (this.current < 0) this.current = this.items.length - 1;
		this.down = false;
		this.fx.start(0);
		this.log('prev : ' + this.current);
	},
	toggle: function() {
		if (this.playing) this.pause();
		else this.play();
	}
});

artpq.Tips = new Class({
	Extends: Tips,
	fireForParent: function(event, element){
		if( element && typeof element.getParent() == 'function' ) {
			var parentNode = element.getParent();
			if (parentNode == document.body) return;
			if (parentNode.retrieve('tip:enter')) parentNode.fireEvent('mouseenter', event);
			else this.fireForParent(parentNode, event);
		} else return;
	}
});

function icon(icon, feature, event) {
	var ext = 'png';
	if (Browser.Engine.trident && Browser.Engine.version < 5) ext = 'gif';
	var img_feature = {'src':'/resource/icons/' + icon + '.' + ext, 'width':16, 'height': 16, 'alt':icon, 'class':'icon button'};
	$extend(img_feature, feature);
	var img = new Element('img', img_feature);
	img.setStyles({
		'vertical-align': 'middle'
	});
	if (event) {
		if ($type(event) == 'object') img.addEvents(event);
		else if ($type(event) == 'function') img.addEvent('click', event.bindWithEvent(img));
	}
	return img;
}

function cprops(el) {
	var props = {};
	if (el.retrieve('cprops')) return el.retrieve('cprops');
	var vals = el.get('class').split(' ').filter(function(cls){return cls.test(':');});
	if (!vals.length){
		el.store('props', props);
	} else {
		vals.each(function(cls){
			var split = cls.split(':');
			if (split[1]) {
				try {
					props[split[0]] = JSON.decode(split[1]);
				} catch(e) {}
			}
		});
		el.store('cprops', props);
	}
	return props;
}
