var feedbackMessageBoard = function(config){
	ITcraft.apply(this, config);
	this.init();
};

feedbackMessageBoard.prototype = {
	_comment: 0,
	object_name: 'MB',
	messages_container: 'message_board_comments',
	pager_container: 'ajax_pager_container',
	message_form_id: 'messageBoard_form',
	total_container: 'total_messages_container',
	send_report_form: 'send_report_form',
	url: '/ajax/feedbacks.php',
	params: {cmd: 'get_messages'},
	
	type: null,
	req_grid_name: '',
	req_last_page: 0,
	
	bannerHTML: '<a href="http://upstack.com/" target="blank" class="banner upstack-bottom" style="margin-bottom:0px;"></a>',
	
	init: function(){
		var form = $(this.message_form_id);

		this.tpl = new Template('<div class="item">'+
			'<table cellpadding="0" cellspacing="0" border="0">'+
			'<tr>'+
				'<td class="comment-num"><span>Comment No.</span><br/>#{number}</td>'+
				'<td class="user-ico"><a href="/users/profile/#{username}"><img src="#{picture}" alt="" /></a><br/><a href="/users/profile/#{username}"><b>#{username}</b></a><br />#{date_added}</td>'+
				'<td class="comment"><div class="comment-wrap"><div class="comment-body"><p id="comment_#{feedback_id}">#{body}</p></div></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#{edit}'+(user_id != null ? '&nbsp;&nbsp;<a class="pointer" onclick = "'+this.object_name+'.reportThis(#{feedback_id}, #{user_id});">Report This</a>' : '')+'</td>'+
			'</tr>'+
			'</table>'+
		'</div>');
		
		if(form){
			this.form_body = form['f[body]'];
			if(this.form_body){
				if(typeof this.form_body.observe != "function"){
					this.form_body = $(this.form_body);
				}
				this.form_body.observe('click', this.hideLabel);
				this.form_body.observe('blur', this.showLabel);
			}

			new ITcraft.ajaxForm({
				form: this.message_form_id,
				form_body: this.form_body,
				mask_element: 'messageBoard_form',
				listeners: {
					onSuccess: function(d) {
						this.form_body.setValue(this.form_body.defaultValue);
						this.reloadGrid('?grid='+this.req_grid_name+'&page='+(this.req_last_page + (this.displayed_items < this.pageSize ? 0 : 1))+'&object_id='+this.object_id);
					},
					scope: this
				},
				_onSubmit: function() {
					ITcraft._loadMask(this.mask_element, true);
					if(this.form_body.defaultValue == this.form_body.getValue() || this.form_body.getValue() == ''){
						ITcraft.showAlert('Comment must be entered.', 'Message', function(){ITcraft._loadMask(this.mask_element)}, this);
					}else{
						this.form.request({
							onComplete: this._onRequestComplete.bind(this)
						});
					}
					return false;
				}
			});
		}
		this.initGrid();
	},
	initGrid: function(){
		this.reloadGrid('?object_id='+this.object_id);
	},

	hideLabel: function(el){
		if(this.defaultValue == this.getValue()){
			this.setValue('');
		}
	},
	showLabel: function(el){
		if(this.getValue() == ''){
			this.setValue(this.defaultValue);
		}
	},
	_getPager: function(pager, name){
		var links = [];
		for(var i = 0; i < pager.links.length; i++ ){
			var val = pager.links[i];
			if (val.current && val.page != 0){
				links.push('<a class="prev pointer" onclick="'+this.object_name+'.reloadGrid(\'?grid='+name+'&page=0&object_id='+this.object_id+'\');">First</a>');
				links.push('<a class="prev pointer" onclick="'+this.object_name+'.reloadGrid(\'?grid='+name+'&page='+(val.page-1)+'&object_id='+this.object_id+'\');">Previous</a>');
			}
		}
		if (pager.total > 1){
			for(var i = 0 ; i < pager.links.length; i++){
				var val = pager.links[i];
				if(val.current){
					links.push('<span class="current">'+val.name+'</span>');
				}else{
					if(val.show){
						links.push('<a class="pointer" onclick="'+this.object_name+'.reloadGrid(\'?grid='+name+'&page='+val.page+'&object_id='+this.object_id+'\');">'+val.name+'</a>');
					}
				}
				if((i != pager.links.length-1) && (!val.show) && (pager.links[i+1] && pager.links[i+1].show)){
					links.push('...');
				}
			}
		}
		for(var i = 0; i < pager.links.length; i++){
			var val = pager.links[i];
			if(val.current && val.page != (pager.links.length)-1){
				links.push('<a class="next pointer" onclick="'+this.object_name+'.reloadGrid(\'?grid='+name+'&page='+(val.page+1)+'&object_id='+this.object_id+'\');">Next</a>');
				links.push('<a class="next pointer" onclick="'+this.object_name+'.reloadGrid(\'?grid='+name+'&page='+(pager.total-1)+'&object_id='+this.object_id+'\');">Last</a>');
			}
		}
		return this.bannerHTML+'<div class="pager"><table cellspasing="5" cellpadding="0" border="0"><tr><td>'+links.join('</td><td>')+'</td></tr></table></div>';
	},

	prev_messages_counter: 0,
	pageSize: 10,
	_getMessagesHTML: function(data){
		var content = '<div id="additional_messages_box"></div>';
		for(var i = 0 ; i < data.total ; i++){
			content += this._getMessageHTML(data.list[i], i)
		}
		return content;
	},
	_getMessageHTML: function(data, index) {
		if (!data) return '';
		
		if(user_id > 0 && (data['user_id'] == user_id || user_role_main == 'ADMIN')){
			data['edit'] = '<a class="pointer" onclick="'+this.object_name+'.editWin('+data['feedback_id']+')">Edit</a>';
			if (user_role_main == 'ADMIN') {
				data['edit'] += '&nbsp;&nbsp;<a class="pointer" onclick="'+this.object_name+'.deleteComment('+data['feedback_id']+')">Delete</a>';
			}
		}
		data['number'] = this.prev_messages_counter + index;
		if (data['number'] < 10) {
			data['number'] = '0' + data['number'];
		}
		return this.tpl.evaluate(data);
	},
	reloadGrid: function(url){
		this._loadMask(true);
		this.params.type = this.type;
		ITcraft.request(url ? this.url+url :this.url,{
			parameters: this.params,
			onSuccess: function(json) {
				if(json.is_error == false){
					var res = json.data;
					this.req_grid_name = res.name;
					this.req_last_page = res.pager.total-1;
					this.displayed_items = res.total;
					this.prev_messages_counter = this.pageSize * res.page + 1;
					if(json.data.total > 0){
						$(this.messages_container).update(this._getMessagesHTML(res));
						$(this.pager_container).update(this._getPager(res.pager, res.name));
						$(this.total_container).update((res.pager.totalRecords < 10 ? '0' : '') + res.pager.totalRecords);;
					}else{
						var entity_type = 'item';
						switch(this.type) {
						case 'brand':
							entity_type = 'logo';
							break;
						case 'profile':
							entity_type = 'user profile';
							break;
						/*case 'directory':
							entity_type = '';
							break;*/
						case 'domain':
						//case 'print':
						//case 'website':
							entity_type = this.type;
							break;
						/*case 'brebranding':
							entity_type = 'logo rebranding';
							break;*/
						}
						$(this.messages_container).update("<div id='additional_messages_box'><center id=\"no_feedbacks\">Be the first to comment on this "+entity_type+".</center></div>");
						$(this.pager_container).update(this.bannerHTML);
					}
					this._loadMask(false);
				}else{
					ITcraft.showAlert(json.messages[0], "Error");
				}
			},
			scope: this
		});
	},
	_loadMask: function(load){
		if(load){
			var element_loader=new Element('div',{id: 'load_window_id'});
			element_loader.setStyle({
				height:'100%',
				width:'100%',
				'text-align':'center',
				background:'#EEEEEE',
				position:'absolute',
				top:'0px',
				left:'0px',
				filter:'alpha(opacity=10)',
				'-moz-opacity':'0.5',
				opacity:'0.5'
			});
			var h = $(this.messages_container).getHeight()/2;
			element_loader.update('<img style="margin: 0 auto; display: block; margin-top:'+(h)+'px;" src="images/blue-loading.gif" alt="Load..." />');
			$(this.messages_container).insert(element_loader);
		}else{
			setTimeout(function(){
				if($('load_window_id')) $('load_window_id').remove();
			}, 500);
		}
	},
	editWin: function(id){
		var v = $('comment_'+id);
		if (!v) return;

		this.feedback_win = ITcraft.ut.getDialog({
			width: 420,
			height: 280,
			close: 'destroy'
		},{
			ajax_content: {
				parameters: {
					type: 'edit_feedback',
					feedback_type: this.type,
					object_id: this.object_id,
					feedback_id: id
				}
			},
			formConfig: {
				listeners: {
					onSuccess: function(d) {
						var v  = $('comment_'+d.id);
						if(v){
							v.update(d.body);
						}
						this.feedback_win.destroy();
					},
					scope: this
				}
			}
		});
		this.feedback_win.show();
	},
	
	deleteComment: function(id){
		if (id < 1) return;
		var onOk = function(){
			ITcraft.request(this.url,{
				parameters: {
					cmd: 'delete_feedback',
					object_id: this.object_id,
					type: this.type,
					feedback_id: id
				},
				onSuccess: function(json) {
					//need remove html element!
					this.reloadGrid('?object_id='+this.object_id);
				},
				scope: this
			});
		};
		
		ITcraft.showConfirm('Are you sure want to delete this comment?', null,
			onOk,
			this
		);
	},

	reportThis: function(feedback_id){
		BrowseAll.reportThis(feedback_id, this.object_id);
		return;
	}
};