// reference local blank image
Ext.BLANK_IMAGE_URL = '/ext/resources/images/default/s.gif';
//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

// turn on validation errors beside the field globally
Ext.form.Field.prototype.msgTarget = 'side';

// enable tooltips and define set_tt to handle them
Ext.QuickTips.init();
Ext.QuickTips.enable();

function set_tt() {
	this.el.dom.qtip = this.tooltip.text;
	this.el.dom.qtitle = this.tooltip.title;
}

// create namespace
Ext.namespace('sharedIdeas');

var IdeaEditor = function(config){ this.config = config; }

IdeaEditor.prototype = {

	imagepreviewTemplate: new Ext.XTemplate(
		'<div style="margin:8px"><img src="/imsuser/image.cfm?id={imageid}&view=thumb"></div>'
	),

	show: function(opts){
		if (!this.win) {
			this.imagepreviewTemplate.compile();
			var cfg = {
				layout: 'fit',
				minHeight: 600,
				width: 600,
				y: 20,
				autoHeight: true,
				modal: true,
				closeAction: 'hide',
				border: false,
				autoScroll: true, // set this on so cursor shows properly in dialogs 
				items: [{
					region: 'center',
					autoWidth: true,
					autoHeight: true,
					items: [this.form = new Ext.FormPanel({
						fileUpload: true,
						labelAlign: 'top',
						border: false,
						monitorValid: true,
						trackResetOnLoad: true,
						bodyStyle: 'padding:10px;',
						defaults: { width: 540 },
						items: [
							{ name: 'categoryid', xtype: 'hidden', value: opts.categoryid },
							{ name: 'imageid', xtype: 'hidden', value: '' },
							{ xtype: 'label', html: '<h2>'+opts.posttitle+'</h2><br>'},
							{ layout: 'column', border: false,
							  items: [
							  	{ columnWidth: .5, layout: 'form', border: false, defaults: { width: 200 },
								  items: [
									{ fieldLabel: 'Your First Name', name: 'firstname', xtype: 'textfield', itemCls: 'required', allowBlank: false,
										autoCreate: {tag: 'input', type: 'text', maxlength: '25', autocomplete: 'on'} },
									{ fieldLabel: 'Your City', name: 'city', xtype: 'textfield', itemCls: 'required', allowBlank: false,
										autoCreate: {tag: 'input', type: 'text', maxlength: '25', autocomplete: 'on'} }
								  ]
								},
							  	{ columnWidth: .5, layout: 'form', border: false, defaults: { width: 200 },
								  items: [
									{ fieldLabel: 'Your State or Province', name: 'state', xtype: 'combo', maxLength: 40, itemCls: 'required', allowBlank: false,
										store: new Ext.data.JsonStore({
											autoLoad: true,
											url: '/components/sharedideas_json.cfc',
											baseParams: { method: 'getStates' },
											root: 'data',
											totalProperty: 'recordcount',
											fields: [{ name: 'statename', mapping: 'STATENAME' }]
										}),
										displayField: 'statename',
										autoWidth: true,
										mode: 'local',
										typeAhead: true,
										editable: true,
										forceSelection: false,
										triggerAction: 'all'
									},		
									{ fieldLabel: 'Your Country', name: 'country', xtype: 'combo', maxLength: 40, itemCls: 'required', allowBlank: false,
										store: new Ext.data.JsonStore({
											autoLoad: true,
											url: '/components/sharedideas_json.cfc',
											baseParams: { method: 'getCountries' },
											root: 'data',
											totalProperty: 'recordcount',
											fields: [{ name: 'countryname', mapping: 'COUNTRYNAME' }]
										}),
										displayField: 'countryname',
										value: 'United States',
										autoWidth: true,
										mode: 'local',
										typeAhead: true,
										editable: true,
										forceSelection: false,
										triggerAction: 'all'
									}  
								  ]
								}
							  ]
							},
							{ fieldLabel: 'Your Memory (2000 characters or less)', name: 'content', xtype: 'textarea', 
							  grow: true,
							  growMax: '200',
							  maxLength: 2000, 
							  maxLengthText: 'Your message exceeds 2000 characters', itemCls: 'required', 
							  maskRe: /[^<>]/,
							  stripCharsRe: /<[^>]*>/g,
							  allowBlank: false 
							},
							{ layout: 'column', border: false, id: 'ideaeditor-postimage',
							  items: [
								  { columnWidth: .6, layout: 'form', border: false,
								  	items: [
									{ xtype: 'fileuploadfield', name: 'uploadfile', id: 'uploadfile', 
									  fieldLabel: 'Upload a Photo (optional, limit: 1 photo less than 2 Mb)', width: 250,
									  listeners: { fileselected: { fn: this.uploadImage, scope: this } }
									}]
								  },
								  { columnWidth: .4, layout: 'form', border: false,
								  	items: [{ xtype: 'panel', id: 'image-preview', frame: false, border: false }]
								  }
							  ]
							},	
							{ xtype: 'checkbox', hideLabel: true, name: 'acceptterms', ctCls: 'required', inputValue: '1',
							  boxLabel: 'I accept the following Terms and Conditions'
							},
							{ xtype: 'panel', autoLoad: '/includes/share_terms.cfm', height: 150, frame: true, autoScroll: true }
						],
						listeners: {
							clientvalidation: {
								fn: function(formElm, isvalid){
									var btn = this.win.buttons[0];
									if (isvalid && btn.disabled) { btn.enable(); }
									else if (!isvalid && !btn.disabled) { btn.disable(); }
								}, scope: this
							}
						}
					})]
				}],
				
				buttons: [
				{ text: 'Submit', disabled: true, handler: this.save, scope: this }, 
				{ text: 'Cancel', handler: function(){ this.win.hide(); }, scope: this }
				],
				listeners: { hide: { fn: function(winElm){ this.form.stopMonitoring(); }, scope: this } }
			};
			
			Ext.apply(cfg, this.config);
			this.win = new Ext.Window(cfg);
			if( !opts.allowimages ) { Ext.getCmp('ideaeditor-postimage').hide(); }
		}
		this.win.show();
		this.form.startMonitoring();
	},
	
	uploadImage: function() {
		var filename = this.form.getForm().findField('uploadfile').value;
		filename = filename.replace(/^\s|\s$/g, ""); //trims string
        if (filename.match(/([^\/\\]+)\.(jpg|jpeg|png|gif)$/i)) {
			this.win.el.mask('Uploading your image...', 'x-mask-loading');
			this.form.getForm().submit({
				url: '/components/sharedideas_json.cfc',
				params: { method: 'uploadImage', filefield: 'uploadfile' },
				clientValidation: false,
				success: function(form, action) {
					var responseObj = Ext.util.JSON.decode(action.response.responseText);
					var imageid = responseObj.data.id;
					this.imagepreviewTemplate.overwrite(Ext.getCmp('image-preview').body, { imageid: imageid });
					Ext.getCmp('uploadfile').reset();
					this.form.getForm().findField('imageid').setValue(imageid);
					this.win.el.unmask();												
				},
				failure: function(form, action){
					this.win.el.unmask();
					Ext.getCmp('uploadfile').setValue('');
					var responseObj = Ext.util.JSON.decode(action.response.responseText);
					var msg = responseObj.data.message;
					if (msg == 'invalid file') { alert('Unsupported image type selected'); }
					else if (msg == 'file too large') { alert('File too large - please limit your image file to 2 Mb.'); }
					else { alert('Image upload failed.'); }
				},
				scope: this
			});
		}
		else {
			alert('The file you selected is not a supported image type');
			Ext.getCmp('uploadfile').setValue('');
		}
	},
	
	save: function(){
		var f = this.form.getForm();
		if( f.findField('acceptterms').checked ) {
			this.win.el.mask('Saving...', 'x-mask-loading');
			f.submit({
				url: '/components/sharedideas_json.cfc',
				params: { method: 'submitSharedIdea' },
				success: function(form, action){ window.location = './'; },
				failure: function(){
					this.win.el.unmask();
					alert('Error connecting to server');
				},
				scope: this
			});
		}
		else { Ext.Msg.alert('Status', 'In order to submit a memory or comment, you must read and accept (by clicking on the check box) the Terms and Conditions.'); }
	}
	
};

var CommentEditor = function(config){
	this.config = config;
}

CommentEditor.prototype = {
	show: function(opts){
		if (!this.form) {
			this.form = new Ext.FormPanel({
				style: 'margin-top: 10px',
				labelAlign: 'top',
				border: true,
				frame: true,
				monitorValid: true,
				trackResetOnLoad: true,
				bodyStyle: 'padding:10px;',
				defaults: { width: 540 },
				items: [
					{ name: 'ideaid', xtype: 'hidden', value: opts.ideaid },
					{ xtype: 'label', html: '<h2>Post a Comment</h2>'},
					{ layout: 'column', border: false,
					  items: [
					  	{ columnWidth: .5, layout: 'form', border: false, defaults: { width: 200 },
						  items: [
							{ fieldLabel: 'Your First Name', name: 'firstname', xtype: 'textfield', itemCls: 'required', allowBlank: false,
								autoCreate: {tag: 'input', type: 'text', maxlength: '25', autocomplete: 'on'} },
							{ fieldLabel: 'Your City', name: 'city', xtype: 'textfield', itemCls: 'required', allowBlank: false,
								autoCreate: {tag: 'input', type: 'text', maxlength: '25', autocomplete: 'on'} }
						  ]
						},
					  	{ columnWidth: .5, layout: 'form', border: false, defaults: { width: 200 },
						  items: [
							{ fieldLabel: 'Your State or Province', name: 'state', xtype: 'combo', maxLength: 40, itemCls: 'required', allowBlank: false,
								store: new Ext.data.JsonStore({
									autoLoad: true,
									url: '/components/sharedideas_json.cfc',
									baseParams: { method: 'getStates' },
									root: 'data',
									totalProperty: 'recordcount',
									fields: [{ name: 'statename', mapping: 'STATENAME' }]
								}),
								displayField: 'statename',
								autoWidth: true,
								mode: 'local',
								typeAhead: true,
								editable: true,
								forceSelection: false,
								triggerAction: 'all'
							},		
							{ fieldLabel: 'Your Country', name: 'country', xtype: 'combo', maxLength: 40, itemCls: 'required', allowBlank: false,
								store: new Ext.data.JsonStore({
									autoLoad: true,
									url: '/components/sharedideas_json.cfc',
									baseParams: { method: 'getCountries' },
									root: 'data',
									totalProperty: 'recordcount',
									fields: [{ name: 'countryname', mapping: 'COUNTRYNAME' }]
								}),
								displayField: 'countryname',
								value: 'United States',
								autoWidth: true,
								mode: 'local',
								typeAhead: true,
								editable: true,
								forceSelection: false,
								triggerAction: 'all'
							}  
						  ]
						}
					  ]
					},
					{ fieldLabel: 'Your Comment (2000 characters or less)', name: 'content', xtype: 'textarea', itemCls: 'required', allowBlank: false,
					  maxLength: 2000, maxLengthText: 'Your message exceeds 2000 characters', 
					  grow: true,
					  growMax: 200,
					  maskRe: /[^<>]/,
					  stripCharsRe: /<[^>]*>/g
					},
					{ xtype: 'checkbox', hideLabel: true, name: 'acceptterms', ctCls: 'required', inputValue: '1',
					  boxLabel: 'I accept the following Terms and Conditions' },
					{ xtype: 'panel', autoLoad: '/includes/share_terms.cfm', height: 150, frame: true, autoScroll: true }
				],
				buttons: [
				{ text: 'Submit', disabled: true, formBind: true, handler: this.save, scope: this }, 
				{ text: 'Cancel', handler: function(){ this.form.hide(); }, scope: this }
				],
				listeners: {
					hide: { fn: function(elm){ this.form.stopMonitoring(); }, scope: this }
				}
			});
			this.form.render(opts.container);
		}
		else {
			this.form.getForm().findField('ideaid').setValue(opts.ideaid);
			this.form.getEl().appendTo(opts.container);
			this.form.show();
		}
		this.form.startMonitoring();
	},
		
	save: function(){
		var f = this.form.getForm();
		if( f.findField('acceptterms').checked ) {
			this.form.getEl().mask('Saving...', 'x-mask-loading');
			f.submit({
				url: '/components/sharedideas_json.cfc',
				params: { method: 'submitSharedIdeaComment' },
				success: function(form, action){
					this.form.getEl().unmask();
					var responseObj = Ext.util.JSON.decode(action.response.responseText);
					if (responseObj.success) {
						this.form.hide();
						window.location.reload();
					} else { alert('Failed to save your message.'); }
				},
				failure: function(){
					this.form.getEl().unmask();
					alert('Error connecting to server');
				},
				scope: this
			});
		}
		else { Ext.Msg.alert('Status', 'In order to submit a comment, you must read and accept (by clicking on the check box) the Terms and Conditions.'); }
	}
};

var ViolationEditor = function(config){
	this.config = config;
}

ViolationEditor.prototype = {
	show: function(opts){
		if (!this.form) {
			this.form = new Ext.FormPanel({
				style: 'margin-top: 10px;margin-bottom: 10px',
				labelAlign: 'top',
				border: true,
				frame: true,
				monitorValid: true,
				trackResetOnLoad: true,
				bodyStyle: 'padding:10px;',
				items: [
					{ name: 'ideaid', xtype: 'hidden', value: opts.ideaid },
					{ name: 'commentid', xtype: 'hidden', value: opts.commentid },
					{ xtype: 'label', html: '<h2>Report a Violation</h2>'},
					{ xtype: 'radiogroup',
                         fieldLabel: 'To report a violation of the Wilton.com terms and conditions, please select the option below that best describes the violation',
						 name: 'violation',
						 id: 'violation',
						 allowBlank: false,
						 columns: [.3,.3,.4],
                         items: [
                             {boxLabel: 'Improper language', name: 'violation', inputValue: 'Improper language' },
                             {boxLabel: 'Copyrighted information', name: 'violation', inputValue: 'Copyrighted information' },
                             {boxLabel: 'Advertisement/solicitation', name: 'violation', inputValue: 'Advertisement/solicitation' },
                             {boxLabel: 'Duplicate post', name: 'violation', inputValue: 'Duplicate post' },
                             {boxLabel: 'Offensive image', name: 'violation', inputValue: 'Offensive image' },
                             {boxLabel: 'Image contains photo of a child', name: 'violation', inputValue: 'Image contains photo of a child' },
                             {boxLabel: 'Other', name: 'violation', inputValue: 'Other' }
                         ]
                    },
					{ fieldLabel: 'Additional Comments (optional)', name: 'comment', xtype: 'textarea', width: 550, 
					  allowBlank: true,
					  maxLength: 500,
					  maxLengthText: 'Your message exceeds 500 characters',
					  maskRe: /[^<>]/,
					  stripCharsRe: /<[^>]*>/g
 					}
				],
				buttons: [
				{ text: 'Submit', disabled: true, formBind: true, handler: this.save, scope: this }, 
				{ text: 'Cancel', handler: function(){ this.form.hide(); }, scope: this }
				],
				listeners: {
					hide: { fn: function(elm){ this.form.stopMonitoring(); }, scope: this }
				}
			});
			this.form.render(opts.container);
		}
		else {
			this.form.getForm().findField('ideaid').setValue(opts.ideaid);
			this.form.getForm().findField('commentid').setValue(opts.commmentid);
			this.form.getEl().appendTo(opts.container);
			this.form.show();
			
		}
		this.form.startMonitoring();
	},
		
	save: function(){
		var f = this.form.getForm();
		var violation = f.findField('violation').getValue();
		this.form.getEl().mask('Saving...', 'x-mask-loading');
		f.submit({
			url: '/components/sharedideas_json.cfc',
			params: { method: 'submitSharedIdeaViolation' },
			success: function(form, action){
				this.form.getEl().unmask();
				var responseObj = Ext.util.JSON.decode(action.response.responseText);
					this.form.hide();
					Ext.Msg.alert('', 'Thank you for reporting this violation. The post will be removed until it has been reviewed.',
						function() { 
							var commentid = this.form.getForm().findField('commentid').value;
							if( commentid != '' ) { window.location.reload(); }
							else {
								if( window.location.pathname.search('idea.cfm') != -1 ) { window.location = './'; }
								else { window.location.reload(); }
							}
						}, this );
			},
			failure: function(){
				this.form.getEl().unmask();
				alert('Error connecting to server');
			},
			scope: this
		});
	}
};

// create application
sharedIdeas.app = function() {
    // do NOT access DOM from here; elements don't exist yet
 
    // private variables
	var ideaEditor = new IdeaEditor();
	var commentEditor = new CommentEditor();
	var violationEditor = new ViolationEditor();
	var posttitle = null;
	
    // public space
    return {
        // public properties, e.g. strings to translate
		
        // public methods
        init: function(opts) {
			Ext.apply(sharedIdeas.app,opts,
						{ posttitle: 'Share Your Idea',
						  allowimages: true });
        },
		
		shareIdea: function(categoryid) {
			ideaEditor.show({
				categoryid: categoryid,
				posttitle: this.posttitle,
				allowimages: this.allowimages
			});
		},
		
		shareIdeaComment: function(ideaid, container) {
			commentEditor.show({
				ideaid: ideaid,
				container: container
			});
		},

		shareIdeaViolation: function(ideaid, commentid, container) {
			violationEditor.show({
				ideaid: ideaid,
				commentid: commentid,
				container: container
			});
		}
    };
}(); // end of app