var comments_store;
var sendComment;
var photo_id=0;//will be set only in extjs_album where it is needed
var url = location.href;
if (url.search(/#/)>0) {
	var position = url.search(/#/);
	url = url.substr(0,position);
}

function delete_comment(id){
	Ext.Ajax.request({
		url: url+'&comment_remove',
		method: 'post',
		params:{
			id: id
		},
		// check the response from the server and remove the comment
		callback: function(options, success, response){	        
			if(success==true){
				$('#comment-'+id).fadeOut('slow', function() {$('#comment-'+id).hide()});
			}
		}
	});
}
	
Ext.onReady(function(){
		
	Ext.QuickTips.init();
/*
	BoxButton = Ext.extend(Ext.BoxComponent, Ext.apply({
	        constructor: Ext.Button
	    }, Ext.Button.prototype)
	);
	Ext.reg('boxbutton', BoxButton);
	
	Ext.override(Ext.BoxComponent, {
	    adjustSize : function(w, h){
	        if(this.autoWidth === true){
	            w = 'auto';
	        }
	        if(this.autoHeight === true){
	            h = 'auto';
	        }
	        return {width : w, height: h};
	    }
	});
*/
	/*
	 * ================  Comments =======================
	 */
	
	// format the data returned from the server before displays on the View
	var formatDataComment = function(data){
		//change from php date format to javascript. You might not need it.
		data.dateString = new Date(data.created).format("j M Y");
		return data;
	};
	
	// we'll use this record inside the store and later to create add a new comment
	var commentRecord = Ext.data.Record.create([
		{name:'id'},
		{name:'mem_id'},
		{name:'name'},
		{name:'link'},
		{name:'photo'},
		{name:'group_admin'},
		{name:'owner'},
		{name:'created', type:'date', dateFormat:'timestamp'},
		{name:'comment', type: 'string'}
	]);
	
	comments_store = new Ext.data.JsonStore({
			url: url+"&get_comments",
			autoLoad: true,
			root: 'comments',
			fields: commentRecord
		});

	var commentsView = new Ext.DataView({
		// define the html element that will be used when a user click on a comment. 
		itemSelector: 'div.comment',
		store: comments_store,
		tpl: new Ext.XTemplate(
			'<tpl for=".">',
			'<div class="comment" id="comment-{id}">',
				'<div class="comment-photo">',
					'<img src="{photo}" alt="{name}" />',
				'</div>',
				'<div class="comment-text">',
					'<div class="comment-title">',
						'<div class="comment-left"><span class="comment-date">{dateString}</span> <span class="comment-name">{link}</span></div>',
						'<tpl if="owner"><div class="comment-right"><a href="javascript:delete_comment({id})">(X)</a></div></tpl>',
					'</div>',
					'<div class="comment-entry">',
						'<tpl if="group_admin">',
							'<span style="font-weight:bold;">',
						'</tpl>',
						'{comment}',
						'<tpl if="group_admin">',
							'</span>',
						'</tpl>',
					'</div>',
				'</div>',
			'</div>',
			'</tpl>'
		),
		prepareData: formatDataComment.createDelegate(this),
		loadingText: 'Loading... Please wait...'
	});	
	
	//---------EndComment ---------------------------------------------------------------------
	
	/*
	 * ================ ADD Comment =======================
	 */
	
	// send the comment to the server, load the store and display it 
	sendComment = function(comment){
		Ext.Ajax.request({
			url: url+'&comment_add_remove',
			method: 'post',
			params:{
				comment: comment,
				master_id: photo_id
			},
			// check the response from the server and add the comment
			callback: function(options, success, response){
				if(success==true){
					var result = Ext.decode(response.responseText)
					var rcrd = new commentRecord({
						id: result.id,
					    created: result.created,
					    comment: result.comment
					});
					commentsView.store.reload();
					Ext.fly('btn-add-comment').update('<img id="post_comment" src="'+g_params["static_media_domain"]+'/public/global/post-btn.jpg" alt="Post Comment" />');
					document.getElementById("comment").value = "Post Your Comment Here";
					document.getElementById("btn-add-comment").onclick = post_the_comment;
				}
			}
		});
	};
		
	//----------------------------------------------------------------------------------------
	/*	
	var addCommentBtn = new  Ext.Button({
		id: 'btn-add-comment',
		width:48,
		text: '<img id="post_comment" src="'+g_params["static_media_domain"]+'/public/global/post-btn.jpg" alt="Post Comment" />', //add coment
		handler: function(){
			var commentTextArea = Ext.getCmp('comment');

			commentTextArea.clearInvalid(); //Clear any invalid styles/messages for this field
			
			//send the comment
			if(fake_user)
				open_login_popup();
			else
				sendComment(commentTextArea.getValue());
			
			//clear the comment from the text area
			commentTextArea.reset();  
		},
		scope: this
	});

	if (allow_post && !fake_user) {
		var commentsPostBox = {
			layout:'column',
		   	bodyStyle:'padding-top:1px',
			width:500,
			border:false,
			items: [
			{
				border:false,
				width:56,
				html:'<div class="comment-photo"><img alt="'+photo_alt+'" src="'+photo_src+'" /></div>'
			},
			{
				xtype: 'textarea',
				width: 382,
				height: 56,
				hideLabel: true,
				emptyText: 'Post Your Comment Here',
				id: 'comment'
			},
				addCommentBtn
			]
		};
	}
	else {
		var commentsPostBox = {
			width:500,
			border:false,
			id: 'comments_not_allowed',
			html: (first_name ? "Only "+first_name+"'s friends can post comments on "+gender+" profile" : '<a href="javascript:open_login_popup();">Only members can post comments</a>')
		};
	}*/
	//---------End  Add Comment ---------------------------------------------------------------------
	
	/*
	 * ================  Comment Form =======================
	 */
	var comment_form = new Ext.FormPanel({
	    collapsible: false,
	    region: 'center',
	    autoScroll: true,
	    frame: false,
	    width: 500,
	    border:false,
	    url: url,
		id: 'comment-form',
	    layout: 'form',
	    bodyStyle: 'background:transparent;',
		items: [
			//commentsPostBox,
			commentsView
		],
		renderTo: comments_render
	});
	
	comment_form.on({
        actioncomplete: function(form, action){
            if(action.type == 'load'){
                comment_form.syncSize(); 
            }
        }
    });    
});

function post_the_comment(){
	if (document.getElementById("comment").value!="" && document.getElementById("comment").value!="Post Your Comment Here"){
		sendComment(document.getElementById("comment").value);
		Ext.fly('btn-add-comment').update('<div class="loading-indicator">Posting...</div>');
		document.getElementById("btn-add-comment").onclick = "";
	}
}