//Data arrays for Score/Rating comboboxes (1.0 - 10.0).
Ext.namespace('Ext.reviewScoreStore');

Ext.onReady(function(){
	// turn on validation errors beside the field globally
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	
	//Get review scores data from XML...
	Ext.reviewScoreStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: '../_includes/data_stores/review_scores.xml'}),
		reader: new Ext.data.XmlReader({record: 'row'}, ['score', 'scoreDisplay'])
	});
});

//Create the ReviewConsole application (single instance)
var ReviewConsole = function(){
    
    // define some private variables
    var dialog, reviewGameButton, reviewForm, wordCountMin, pickGame, gameSelected, reviewDetails;
	
	//Settings
	wordCountMin = {
		overallDesc: 75,
		otherDesc: 50
	}
	
	getProductId = function(){
		return $F('reviewDialog-ProductId');	
	},
	setProductId = function(value){
		$('reviewDialog-ProductId').value = value;	
	},
    
	//Submit form to server.
	submitReview = function(){
		if (!reviewForm){
			Ext.Msg.alert('Error - Unable to Submit Review', 'Select a game before trying to submit your review... wiseguy.');
			return;
		}
		
		if (reviewForm.isValid()){
			reviewForm.submit({
				params:{
					product_id: getProductId()
				},
				waitMsg:'Saving...',
				success: function(reviewForm, action) {
					//Ext.MessageBox.alert('Success', action.result.data[0].responseMsg);
					dialog.hide();
					window.location = '/product_profile/'+getProductId()+'.html';
				},
				failure: function(reviewForm, action) {
					Ext.MessageBox.alert('Error', action.result.data[0].responseMsg);
					dialog.hide();
				}
			});	
		}
		else{
			var errMsg = 'Your review has one or more errors that must be resolved before you can submit your review.';
			errMsg += ' Please correct the errors and try again.';
			errMsg += '<br /><br /><b>Tip:</b><br />The <span style="background:url(../../_includes/javascripts/ext/resources/images/default/grid/invalid_line.gif) repeat-x scroll center bottom">red squiggly line</span> helps you find fields that must be corrected';
			errMsg += ', and when you hover your mouse over the <img src="../../_includes/javascripts/ext/resources/images/default/form/exclamation.gif" width="16" height="16" /> icon, it will provide hints as to what exactly the problem is with that field.';
			Ext.Msg.alert('Error - Unable to Submit Review', errMsg);
		}
	};
	
	//Validation functions.
	isWordCountReached = function(val, minWordCount){
		return (val.split(' ').length >= minWordCount);
	};
	
	pickGame = function(){
		new Ajax.Autocompleter(
			"GameSearchConsole", 
			"GameSearchResultsConsole", 
			"/_includes/game_search.php", {
				minChars: 2,
				afterUpdateElement: gameSelected
			}
		);
		
		$('reviewForm').hide().previous('div').setStyle({height: '99%'});
	};
	gameSelected = function(inputEl, liEl){
		$('reviewForm').show().previous('div').setStyle({height: ''}).update(inputEl.value);
		setProductId(liEl.id);
		reviewDetails();
	};
	
	reviewDetails = function(){
		//Get data from this user/product to pre-populate the form with..
		var reviewFormData = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: '/_includes/review_dialog_get.php?ProductId=' + getProductId()}),
			reader: new Ext.data.JsonReader({},['overall_description', 'overall_rating', 
												'gameplay_description', 'gameplay_rating', 
												'visual_description', 'visual_rating', 
												'audio_description', 'audio_rating', 
												'developer_suggestions']
											),
			remoteSort: false
		});
		
		reviewFormData.on('load', function(){
										   
			/* START form params and initialization */
				reviewForm = new Ext.form.Form({
					url:'/_includes/review_dialog_save.php',
					autoCreate: false,
					labelAlign: 'top',
					labelWidth: 175,
					buttonAlign: 'right'
				});
				
				//Container for tabs
				var frmContainerTabs = reviewForm.container();
				reviewForm.end();
				
				//Create tabs.
				var frmTabs = new Array();
				frmTabs[0] = 
				{
					title: 'Overall',
					container:
						reviewForm.container(
							{el:Ext.DomHelper.append(Ext.get('reviewForm'), {tag:'div', cls:'x-dlg-form-container'})}
						)
				};
				reviewForm.container(
					{},
					new Ext.form.TextArea({
						fieldLabel: 'Overall Description ('+wordCountMin.overallDesc+' words or more)',
						name: 'overall_description',
						value: reviewFormData.getAt(0).data.overall_description,
						width: 550,
						height: 175,
						allowBlank: false,
						validator: function(val){
							return isWordCountReached(val, wordCountMin.overallDesc);	
						},
						invalidText: wordCountMin.overallDesc + ' or more words required in this field'
					})
				);
				
				var cb = new Ext.form.ComboBox({
							fieldLabel: 'Overall Rating',
							hiddenName: 'overall_rating',
							store: Ext.reviewScoreStore,
							displayField: 'scoreDisplay',
							valueField: 'score',
							triggerAction: 'all',
							emptyText:' - ',
							width:100,
							editable:false,
							allowBlank: false
						});
				if (reviewFormData.getAt(0).data.overall_rating){
					cb.value = reviewFormData.getAt(0).data.overall_rating;
				}
				reviewForm.column({width:'25%'}, cb);
				
				var cb = new Ext.form.ComboBox({
							fieldLabel: 'Gameplay Rating',
							hiddenName: 'gameplay_rating',
							store: Ext.reviewScoreStore,
							displayField: 'scoreDisplay',
							valueField: 'score',
							triggerAction: 'all',
							emptyText:' - ',
							width:100,
							editable:false,
							allowBlank: false
						});
				if (reviewFormData.getAt(0).data.gameplay_rating){
					cb.value = reviewFormData.getAt(0).data.gameplay_rating;	
				}
				reviewForm.column({width:'25%'}, cb);
				
				var cb = new Ext.form.ComboBox({
							fieldLabel: 'Visual Rating',
							hiddenName: 'visual_rating',
							store: Ext.reviewScoreStore,
							displayField: 'scoreDisplay',
							valueField: 'score',
							triggerAction: 'all',
							emptyText:' - ',
							width:100,
							editable:false,
							allowBlank: false
						});
				if (reviewFormData.getAt(0).data.visual_rating){
					cb.value = reviewFormData.getAt(0).data.visual_rating;
				}
				reviewForm.column({width:'25%'}, cb);
				
				var cb = new Ext.form.ComboBox({
							fieldLabel: 'Audio Rating',
							hiddenName: 'audio_rating',
							store: Ext.reviewScoreStore,
							displayField: 'scoreDisplay',
							valueField: 'score',
							triggerAction: 'all',
							emptyText:' - ',
							width:100,
							editable:false,
							allowBlank: false
						});
				if (reviewFormData.getAt(0).data.audio_rating){
					cb.value = reviewFormData.getAt(0).data.audio_rating;
				}
				reviewForm.column({width:'25%'}, cb);
	
				reviewForm.end();
				
				frmTabs[1] = 
				{
					title: 'Gameplay Description*',
					container:
						reviewForm.container(
							{el:Ext.DomHelper.append(Ext.get('reviewForm'), {tag:'div', cls:'x-dlg-form-container'})},
							new Ext.form.TextArea({
								fieldLabel: 'Gameplay Description* ('+wordCountMin.otherDesc+' words or more)',
								name: 'gameplay_description',
								value: reviewFormData.getAt(0).data.gameplay_description,
								width: 550,
								height: 175,
								validator: function(val){
									return isWordCountReached(val, wordCountMin.otherDesc);	
								},
								invalidText: wordCountMin.otherDesc + ' or more words required in this field'
							})
						)
				};
				frmTabs[2] = 
				{
					title: 'Visual Description*',
					container:
						reviewForm.container(
							{el:Ext.DomHelper.append(Ext.get('reviewForm'), {tag:'div', cls:'x-dlg-form-container'})},
							new Ext.form.TextArea({
								fieldLabel: 'Visual Description* ('+wordCountMin.otherDesc+' words or more)',
								name: 'visual_description',
								value: reviewFormData.getAt(0).data.visual_description,
								width: 550,
								height: 175,
								validator: function(val){
									return isWordCountReached(val, wordCountMin.otherDesc);	
								},
								invalidText: wordCountMin.otherDesc + ' or more words required in this field'
							})
						)
				};
				frmTabs[3] =
				{
					title: 'Audio Description*',
					container:
						reviewForm.container(
							{el:Ext.DomHelper.append(Ext.get('reviewForm'), {tag:'div', cls:'x-dlg-form-container'})},
							new Ext.form.TextArea({
								fieldLabel: 'Audio Description* ('+wordCountMin.otherDesc+' words or more)',
								name: 'audio_description',
								value: reviewFormData.getAt(0).data.audio_description,
								width: 550,
								height: 175,
								validator: function(val){
									return isWordCountReached(val, wordCountMin.otherDesc);	
								},
								invalidText: wordCountMin.otherDesc + ' or more words required in this field'
							})
						)
				};
				frmTabs[4] =
				{
					title: 'Developer Suggestions*',
					container:
						reviewForm.container(
							{el:Ext.DomHelper.append(Ext.get('reviewForm'), {tag:'div', cls:'x-dlg-form-container'})},
							new Ext.form.TextArea({
								fieldLabel: 'Developer Suggestions* ('+wordCountMin.otherDesc+' words or more)',
								name: 'developer_suggestions',
								value: reviewFormData.getAt(0).data.developer_suggestions,
								width: 550,
								height: 175
							})
						)
				};
											   
											   
				//Render form on page.
				reviewForm.render('reviewForm');
				
				//Render tabs.
				var tabPanel = new Ext.TabPanel(frmContainerTabs.el);
				frmTabs.each(function(el){
					tabPanel.addTab(el.container.getEl().id, el.title);
				});
				tabPanel.activate(0);
			/* END form params and initialization */
		});
		reviewFormData.load();
	};
	
    // return a public interface
    return {
        init : function(){
             // attach to click event
            reviewGameButton = $('reviewGameButton');
			if (reviewGameButton){
				reviewGameButton.observe('click', function(event){
					ReviewConsole.showDialog();
					Event.stop(event);
				});
			}
        },

        showDialog : function(){
			
			var userId = $F('reviewDialog-UserId');
			var userGroupId = $F('reviewDialog-UserGroupId');
			
			if (userId==0 || userGroupId!=2){
				//Not a valid user for writing reviews!
				Ext.MessageBox.alert('Error', 'You must <a href="/forums/usercp.php">login</a> before writing a review.');
				return;
			}
			
            if(!dialog){ // lazy initialize the dialog and only create it once		
		
				/* START dialog params */
					dialog = new Ext.BasicDialog("reviewDialog", {
							animateTarget:reviewGameButton,
							modal:true,
							width:600,
							height:400,
							shadow:'drop',
							resizable:false,
							shim:true
					});
					dialog.addKeyListener(27, dialog.hide, dialog); //ESC button to close.
					dialog.addButton('Cancel', dialog.hide, dialog);
					dialog.addButton('Submit', submitReview, dialog);
				/* END dialog params */
				
				//Force the user to pick a game if one is not selected already.
				if (getProductId()==0) pickGame();
				else reviewDetails();
            }
            dialog.show($('modalDialog'));
        }		
    };
}();

// using onDocumentReady instead of window.onload initializes the application
// when the DOM is ready, without waiting for images and other resources to load
Ext.EventManager.onDocumentReady(ReviewConsole.init, ReviewConsole, true);
