var NXC = NXC || {};
NXC.CollectionsCreateWiard = new Class( {

	Implements: [Options, Events],

	options: {
		'ajaxBaseURL': 'php/ajax/',
		'stepHeadlinesCSSPath': 'ul.nxc-collections-create-wizard-steps li',
		'stepHeadlineActiveClass': 'active',
		'stepContainersCSSPath': 'div.nxc-collections-create-wizard-step-container div.nxc-collections-wizard-step',
		'stepContainerActiveClass': 'active',

		'step1UploadImageLinkID': 'nxcCollectionCreateWizardUploadImage',
		'step1UploadImageContainerID': 'nxcCollectionCreateWizardImageContainer',
		'step1ImageUploadProgressBarID': 'nxc-progress-bar-wrapper',
		'step1ImageUploadInputField': 'nxcCollectionCreateWizardImage',
		'step1FormID': 'nxcCollectionCreateWizardStep1Form',
		'step1ContinueButtonID': 'nxcCollectionCreateWizardStep1Continue',
		'step1CancelButtonID': 'nxcCollectionCreateWizardStep1Cancel',
		'swiffPath': './flash/Swiff.Uploader.swf',
		'uploadPHPScript': './php/upload.php',
		'uploadImageMaxSize': 10 * 1024 * 1024,
		'uploadImagesStorage': './var/storage/collection_icons/',

		'step2FormID': 'nxcCollectionCreateWizardStep2Form',
		'step2ContinueButtonID': 'nxcCollectionCreateWizardStep2Continue',
		'step2CancelButtonID': 'nxcCollectionCreateWizardStep2Cancel',
		'step2TypeInputID': 'nxcCollectionCreateWizardType',
		'publicTypeLinkID': 'nxcCollectionCreateWizardTypePublic',
		'privateTypeLinkID': 'nxcCollectionCreateWizardTypePrivate',
		'selectedTypeClass': 'selected-type',

		'step3FormID': 'nxcCollectionCreateWizardStep3Form',
		'step3ContinueButtonID': 'nxcCollectionCreateWizardStep3Continue',
		'step3CancelButtonID': 'nxcCollectionCreateWizardStep3Cancel',

		'step4ContinueButtonID': 'nxcCollectionCreateWizardStep4Continue',
		'step4CancelButtonID': 'nxcCollectionCreateWizardStep4Cancel',

		'inputErrorClass': 'error',
		'inputElementsBase': 'nxc_collections_wizard_',
		'filterBlockID': 'nxcCollectionsFilter',
		'messages': {
			'formInputErrorHeader': 'Required data is either missing or is invalid'
		}
	},

	lightbox: false,
	container: false,
	messageStack: false,
	stepHeadlines: [],
	stepContainers: [],
	collectionID: false,


	step1: {
		'imageUploader': false,
		'imageUploadLink': false,
		'imageUploadContainer': false,
		'imageUploadProgressBar': false,
		'imageInputField': false,
		'continueButton': false,
		'cancelButton': false,
		'form': false,
		'inputs': []
	},

	step2: {
		'typeSelected': false,
		'continueButton': false,
		'cancelButton': false,
		'publicTypeLink': false,
		'privateTypeLink': false,
		'form': false,
		'typeInput': false,
		'selectedTypeClass': false
	},

	step3: {
		'continueButton': false,
		'cancelButton': false,
		'form': false,
		'inputs': []
	},

	step4: {
		'continueButton': false,
		'cancelButton': false
	},

	initialize: function( lightbox, messageStack, options ) {
		this.setOptions( options );

		this.lightbox       = lightbox;
		this.container      = this.lightbox.contentBlock;
		this.stepHeadlines  = this.container.getElements( this.options.stepHeadlinesCSSPath );
		this.stepContainers = this.container.getElements( this.options.stepContainersCSSPath );

		this.messageStack = messageStack;

		this.installStep1();
		this.installStep2();
		this.installStep3();
		this.installStep4();
	},

	installStep1: function() {
		this.step1.imageUploadLink        = document.id( this.options.step1UploadImageLinkID );
		this.step1.imageUploadContainer   = document.id( this.options.step1UploadImageContainerID );
		this.step1.imageInputField        = document.id( this.options.step1ImageUploadInputField );
		this.step1.continueButton         = document.id( this.options.step1ContinueButtonID );
		this.step1.form                   = document.id( this.options.step1FormID );
		this.step1.cancelButton           = document.id( this.options.step1CancelButtonID );
		this.step1.imageUploadProgressBar = new NXC.ProgressBar( this.options.step1ImageUploadProgressBarID );
		this.step1.inputs                 = this.step1.form.getElements( 'input, textarea' );

		this.step1.imageUploader = new Swiff.Uploader( {
			path: this.options.swiffPath,
			url: this.options.uploadPHPScript,
			target: this.step1.imageUploadLink,
			verbose: false,
			queued: false,
			multiple: false,
			instantStart: true,
			appendCookieData: true,
			typeFilter: {
				'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
			},
			fileSizeMax: this.options.uploadImageMaxSize,
			onSelectSuccess: function( files ) {
				this.setEnabled( false );
			},
			onSelectFail: function( files ) {
				var msg =
					files[0].name + ' was not added!<br/>' +
					'Please select an image smaller than 10 Mb.<br/>' +
					'(Error: #' + files[0].validationError + ')';
				this.messageStack.showMessage( msg, 'error' );
			}.bind( this ),
			onFileStart: function() {
				this.step1.imageUploadContainer.setStyle( 'display', 'none' );
				this.step1.imageUploadProgressBar.wrapper.setStyle( 'display', 'block' );
			}.bind( this ),
			onFileProgress: function() {
				if( this.step1.imageUploader.uploading == true ) {
					this.step1.imageUploadProgressBar.progress( this.step1.imageUploader.percentLoaded );
				}
			}.bind( this ),
			onFileComplete: function( file ) {
				if( file.response.error ) {
					var msg =
						'Failed Upload<br/>' +
						'Uploading ' +  file.name + 'failed, please try again.<br/>' +
						'(Error: #' + file.response.code + ' ' + file.response.error + ')';
					this.messageStack.showMessage( msg, 'error' );
				} else {
					var jsonResponse = new Hash( JSON.decode( file.response.text, true ) || {} );
					if( jsonResponse.error ) {
						var msg =
							'Failed Upload <br/>' +
							'Uploading ' +  file.name + ' failed, please try again.<br/>' +
							'(Error: ' + jsonResponse.error + ')';
						this.messageStack.showMessage( msg, 'error' );
					} else {
						this.step1.imageUploadContainer.set( 'src', this.options.uploadImagesStorage + jsonResponse.name );
						this.step1.imageUploadContainer.setStyle( 'display', 'block' );
						this.step1.imageInputField.set( 'value', jsonResponse.name );
					}
				}
				file.remove();

				this.step1.imageUploadProgressBar.wrapper.setStyle( 'display', 'none' );
				this.step1.imageUploadProgressBar.progress( 1, false );
				this.step1.imageUploader.setEnabled( true );
			}.bind( this )
		} );
		this.step1.imageUploader.box.setStyle( 'display', 'none' );

		this.step1.imageUploadLink.addEvents( {
			click: function( e ) { e.stop(); },
			mouseenter: function() {
				this.step1.imageUploader.reposition();
			}.bind( this )
		} );

		this.step1.continueButton.addEvent( 'click', function() {
			new Request.JSON( {
				'url'      : this.options.ajaxBaseURL + '/collection/create',
				'method'   : 'post',
				'onSuccess': function( response ) {
					var response = new Hash( response );
					response.set( 'errors', new Hash( response.get( 'errors' ) ) );

					if( response.get( 'status', 0 ).toInt() === 1 ) {
						this.collectionID = response.get( 'collection_id' );
						this.setActiveStep( 2 );
					} else {
						this.step1.inputs.removeClass( this.options.inputErrorClass );

						var errorMessage = '';
						response.get( 'errors' ).each( function( message, elementName ) {
							errorMessage += '<li>' + message + '</li>';

							var name = this.options.inputElementsBase + elementName;
							this.step1.inputs.each( function( el ) {
								if( el.get( 'name' ) === name ) {
									el.addClass( this.options.inputErrorClass );
								}
							}, this );
						}.bind( this ) );

						this.messageStack.stackBlock.empty();
						errorMessage = this.options.messages.formInputErrorHeader + '<ul>' + errorMessage + '</ul>';
						this.messageStack.showMessage( errorMessage, 'error' );
					}
				}.bind( this )
			} ).send( this.step1.form.toQueryString() );
		}.bind( this ) );


		this.step1.inputs.each( function( el ) {
			el.addEvent( 'focus', function( e ) {
				el.removeClass( this.options.inputErrorClass );
			}.bind( this ) );
		}.bind( this ) );
		this.step1.cancelButton.addEvent( 'click', this.cancel.bind( this, false ) );
	},

	installStep2: function() {
		this.step2.continueButton    = document.id( this.options.step2ContinueButtonID );
		this.step2.cancelButton      = document.id( this.options.step2CancelButtonID );
		this.step2.publicTypeLink    = document.id( this.options.publicTypeLinkID );
		this.step2.privateTypeLink   = document.id( this.options.privateTypeLinkID );
		this.step2.form              = document.id( this.options.step2FormID );
		this.step2.typeInput         = document.id( this.options.step2TypeInputID );
		this.step2.selectedTypeClass = this.options.selectedTypeClass;

		this.step2.publicTypeLink.addEvent( 'click', function( e ) {
			e.stop();
			this.step2.typeInput.set( 'value', '1' );
			this.step2.privateTypeLink.removeClass( this.step2.selectedTypeClass );
			this.step2.publicTypeLink.addClass( this.step2.selectedTypeClass );
		}.bind( this ) );

		this.step2.privateTypeLink.addEvent( 'click', function( e ) {
			e.stop();
			this.step2.typeInput.set( 'value', '2' );
			this.step2.publicTypeLink.removeClass( this.step2.selectedTypeClass );
			this.step2.privateTypeLink.addClass( this.step2.selectedTypeClass );
		}.bind( this ) );

		this.step2.continueButton.addEvent( 'click', function() {
			new Request.JSON( {
				'url'      : this.options.ajaxBaseURL + '/collection/update_type/' + this.collectionID,
				'method'   : 'post',
				'onSuccess': function( response ) {
					var response = new Hash( response );

					if( response.get( 'status', 0 ).toInt() === 1 ) {
						this.setActiveStep( 3 );
					} else {
						this.messageStack.stackBlock.empty();
						errorMessage = this.options.messages.formInputErrorHeader + '<ul><li>' + response.get( 'error' ) + '</li></ul>';
						this.messageStack.showMessage( errorMessage, 'error' );
					}
				}.bind( this )
			} ).send( this.step2.form.toQueryString() );
		}.bind( this ) );

		this.step2.cancelButton.addEvent( 'click', this.cancel.bind( this ) );
	},

	installStep3: function() {
		this.step3.continueButton = document.id( this.options.step3ContinueButtonID );
		this.step3.cancelButton   = document.id( this.options.step3CancelButtonID );
		this.step3.form           = document.id( this.options.step3FormID );
		this.step3.inputs         = this.step3.form.getElements( 'input' );

		this.step3.continueButton.addEvent( 'click', function() {
			new Request.JSON( {
				'url'      : this.options.ajaxBaseURL + '/collection/update_goal/' + this.collectionID,
				'method'   : 'post',
				'onSuccess': function( response ) {
					var response = new Hash( response );
					response.set( 'errors', new Hash( response.get( 'errors' ) ) );

					if( response.get( 'status', 0 ).toInt() === 1 ) {
						this.setActiveStep( 4 );
					} else {
						this.step3.inputs.removeClass( this.options.inputErrorClass );

						var errorMessage = '';
						response.get( 'errors' ).each( function( message, elementName ) {
							errorMessage += '<li>' + message + '</li>';

							var name = this.options.inputElementsBase + elementName;
							this.step3.inputs.each( function( el ) {
								if( el.get( 'name' ) === name ) {
									el.addClass( this.options.inputErrorClass );
								}
							}, this );
						}.bind( this ) );

						this.messageStack.stackBlock.empty();
						errorMessage = this.options.messages.formInputErrorHeader + '<ul>' + errorMessage + '</ul>';
						this.messageStack.showMessage( errorMessage, 'error' );
					}
				}.bind( this )
			} ).send( this.step3.form.toQueryString() );
		}.bind( this ) );

		this.step3.inputs.each( function( el ) {
			el.addEvent( 'focus', function( e ) {
				el.removeClass( this.options.inputErrorClass );
			}.bind( this ) );
		}.bind( this ) );

		this.step3.cancelButton.addEvent( 'click', this.cancel.bind( this ) );
	},

	installStep4: function() {
		this.step4.continueButton         = document.id( this.options.step4ContinueButtonID );
		this.step4.cancelButton           = document.id( this.options.step4CancelButtonID );

		this.step4.continueButton.addEvent( 'click', function() {
			new Request.JSON( {
				'url'      : this.options.ajaxBaseURL + '/collection/confirm/' + this.collectionID,
				'method'   : 'post',
				'onSuccess': function( response ) {
					var response = new Hash( response );

					if( response.get( 'status', 0 ).toInt() === 1 ) {
						var filterBlock = document.id( this.options.filterBlockID );
						if( $type( filterBlock ) == 'element' ) {
							new Request.HTML( {
								'url': this.options.ajaxBaseURL + '/dashboard/get_filter',
								'update': filterBlock
							} ).send();
						}

						this.messageStack.showMessage( response.get( 'notifyMessage' ), 'notice' );
						this.cancel( false );
					} else {
						this.messageStack.stackBlock.empty();
						this.messageStack.showMessage( response.get( 'error' ), 'error' );
					}
				}.bind( this )
			} ).send();
		}.bind( this ) );

		this.step4.cancelButton.addEvent( 'click', this.cancel.bind( this ) );
	},

	setActiveStep: function( stepIndex ) {
		this.step1.imageUploader.box.setStyle( 'display', ( stepIndex == 1 ) ? 'block' : 'none' );

		this.stepHeadlines.removeClass( this.options.stepHeadlineActiveClass );
		this.stepHeadlines[ stepIndex - 1 ].addClass( this.options.stepHeadlineActiveClass );

		this.stepContainers.removeClass( this.options.stepContainerActiveClass );
		this.stepContainers[ stepIndex - 1 ].addClass( this.options.stepContainerActiveClass );
	},

	cancel: function( sendAJAXReuqest ) {
    	if( sendAJAXReuqest === undefined ) {
    		sendAJAXReuqest = true;
    	}

		if( this.collectionID !== false && sendAJAXReuqest === true ) {
			new Request.JSON( {
				'url'      : this.options.ajaxBaseURL + '/collection/cancel/' + this.collectionID,
				'method'   : 'post',
				'onSuccess': function( response ) {}.bind( this )
			} ).send();
		}

		this.step1.imageUploader.box.setStyle( 'display', 'none' );
		this.collectionID = false;
		this.step1.form.reset();
		this.step1.imageUploadContainer.setStyle( 'display', 'none' );
		this.step1.imageInputField.set( 'value', '' );
		this.step3.form.reset();
		this.step2.typeSelected = false;
		this.setActiveStep( 1 );
		this.lightbox.close();
	}
} );
