var challengeLoadMask = null;
var currChallengeID = null;
function addChallengeComment(challenge_id) {
	currChallengeID = challenge_id;
	if ( challengeLoadMask == null ) {
		challengeLoadMask = new Ext.LoadMask('newchallenge');
	}
	challengeLoadMask.show();
	$('add_challenge_comment').request({
		onComplete: function(t) {
			if ( t.responseJSON.success ) {
				challengeLoadMask.hide();
				$('comments_text').value = '';
				new Ajax.Updater('user_comments',HOME_DIR+'challenge_comments/comment_list/'+currChallengeID);
			}
			else {
				Ext.Msg.alert('Error',t.responseJSON.error.reasons);
				challengeLoadMask.hide();
			}
		},
		on404: function() {
			Ext.Msg.alert('Error','Not Found!');
			challengeLoadMask.hide();
		},
		onFailure: function() {
			Ext.Msg.alert('Error','Failed!');
			challengeLoadMask.hide();
		},
		evalJSON: true,
		sanitizeJSON: true
	});
}
var mediaDV = null;
var mediaPanel = null;
var toolBar1 = null;
var toolBar2 = null;
var challenge_id = null;

MediaDataView = function(params,callbackFunc,callbackScope) {
	this.callback = callbackFunc;
	this.callbackScope = callbackScope;
	this.thumbTemplate = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="thumb-wrap" id="{title}">',
			'<div class="thumb"><img src="{thumburl}" title="{title}"></div>',
			'</div>',
		'</tpl>'
	);
	this.thumbTemplate.compile();
    this.store = new Ext.data.JsonStore({
        url: HOME_DIR+'user_images/index',
		baseParams: params,
		method: 'POST',
        root: 'images',
		totalProperty: 'totalCount',
        fields: ['image_id','username','category_name','image','thumb_image','title', 'thumburl', 'fullurl','keywords','artist_comments','image_width','image_height','flag_count']
    });
	MediaDataView.superclass.constructor.call(this,{
		id: 'images-view',
		store: this.store,
		tpl: this.thumbTemplate,
		region: 'center',
		autoHeight:true,
		singleSelect: true,
		overClass:'x-view-over',
		itemSelector:'div.thumb-wrap',
		emptyText: '<div id="no_images">No images to display</div>',
		loadingText: 'Loading...',
		listeners: {
			'selectionchange': {fn:this.showDetails, scope:this, buffer:100}
		}
	});
}
Ext.extend(MediaDataView, Ext.DataView, {
	showDetails: function() {
		var data = this.getSelectedRecords();
		if(data && data.length > 0){
			data = data[0].data;
			if ( typeof(this.callback) == "function" ) {
				this.callback.call(this.callbackScope, this, data);
			}
			else {
				new Ajax.Request(HOME_DIR+'challenge_images/submit/'+challenge_id+'/'+data.image_id, {
					onComplete:function(t) {
						if(mediaPanel != null) mediaPanel.hide();
						mediaDV = null;
						if(t.responseJSON.success) {
							Ext.Msg.alert('Success','Your entry has been received');
						}
						else {
							Ext.Msg.alert('Error',t.responseJSON.errors.reason);
						}
					},
					on404: function() {
			                        Ext.Msg.alert('Error','Not Found!');
			                },
			                onFailure: function() {
                        			Ext.Msg.alert('Error','Failed!');
			                },
			                evalJSON: true,
			                sanitizeJSON: true
				});
			}
		}
	}
});
function displayMedia(params,hidebuttons) {
	if ( typeof(hidebuttons) != 'boolean' ) hidebuttons = false;
		mediaDV = new MediaDataView(params);
		toolbarConfig = {
			pageSize: 16,
			store: mediaDV.store,
			displayInfo: true,
			displayMsg: 'Displaying images {0} - {1} of {2}',
			emptyMsg: "No media to display",
            items:[
                '-', {
                text: 'Upload New',
                cls: 'x-btn-text-icon details',
				icon: HOME_DIR+'images/icons/add.png',
                handler: openUploadWindow
            }]
		};
		toolBar1 = new Ext.PagingToolbar(toolbarConfig);
		toolBar2 = new Ext.PagingToolbar(toolbarConfig);
		mediaPanel = new Ext.Window({
			width: 600,
			height: 400,
			items: [ mediaDV ],
			tbar: toolBar1,
			bbar: toolBar2
		});
   	        mediaPanel.show();
	mediaDV.store.load();
}
function displayChallengeUserMedia(user_id, cid) {
        if(user_id == undefined) {
          Ext.Msg.alert('Error','You must be logged in before submitting a challenge entry.');
          return;
        }
        if(cid == undefined) {
          Ext.Msg.alert('Error','The challenge id was not specified.');
          return;
        }
        challenge_id = cid;
	displayMedia({ browse_type: 'user', site_user_id: user_id, dataview: 'true' });
}
function openUploadWindow() {
	uploadImages();
}
function reloadImages() {
	mediaDV.store.load();
}
