/**
 * Copyright 2007 SK Communications. All rights reserved
 * @since 07.09.16
 * @author okjungsoo
 * 
 *  이오공감 추천평 부분을 관리합니다. 
 */

if(typeof(Modal) == 'undefined') {
//	alert("You must first include Modal.js");
} 

Object.extend(Modal, {
	reportPost: function() {
		if(Modal.current && Modal.current.reportPost) {
			Modal.current.reportPost();
		}
	}
});

Modal.ReviewDlg = Class.create();
Object.extend(Modal.ReviewDlg.prototype, {
	isLoaded: false,
	isFocused: false,
	focusedColor: '#333333',
	
	CONTENT_NOTICE: '이 글을 읽는 분들을 위해 간단하게 추천평을 써주세요. (200자 이하) 추천평에는 ' +
			'상대방에 대한 욕설이나 비방의 내용은 삼가 주시기 바랍니다.',
	
	initialize: function(_dialogID) {
		this.dialogID = _dialogID;
		this.dialog = $(this.dialogID);
		
		this.message = this.dialog.getElementsByClassName('review_message')[0];
		this.content = this.dialog.getElementsByTagName('textarea')[0];
		this.permaLink = (this.dialog.getElementsByTagName('input')[0]).value;

		this.isLoaded = Modal.addDialog(this);
	},
	
	open: function(isVisibleList) {
		this.content.value = this.CONTENT_NOTICE;
		this.content.style.color = "";
		this.message.update('');

		this.isFocused = false;
		this.dialog.show();
	},
	
	close: function() {
		this.dialog.hide();
	},
	
	visible: function() {
		return this.dialog.visible();
	},
	
	setFocus: function(element) {
		if(!this.isLoaded) { return;}
		if(!this.isFocused) {
			element.value = '';
			element.style.color = this.focusedColor;
			this.isFocused = true;
		}
	},
	
	recommendPost: function() {
		var permanentLink = this.permaLink;
		var recommendation = this.content.value.stripScripts().stripTags();
		
		if(this.isValidContent(recommendation)) {
			if(this.isFocused != true) {
				recommendation = '';
			}	
			
			new Ajax.Request('/exec/eofeeling/insert_recommend_exec.php', {
				parameters: $H({
					'eo_permalink': permanentLink,
					'eo_message': recommendation
				}),
				onSuccess: function(response){
					var text = response.responseText;
					
					if(text.isJSON()) {
						var responseArr = text.evalJSON();
						if(responseArr.result == '1') {
							if(typeof(Page) != 'undefined' && Page.refresh) {
								Page.refresh(responseArr.isFirstRecommendation);								
							}else {
								this.close();
							}
						}else if(responseArr.result == '0'){
							this.showErrorMsg(responseArr.message);
						}
					}					
				}.bind(this)
			});
		}
	},
	
	isValidContent: function(content) {
		if(content.length > 200) {
			return this.showErrorMsg('추천평은 200자까지 입력할 수 있습니다.');
		} else {
			return true;			
		}
	},
	
	showErrorMsg: function(content) {
		this.message.innerHTML = content;
		return false;
	}
});
