/**
 * Create a new instance of VCMInscriptionModal
 * @param {VCMPage} page Reference to a VCMPage object
 * @return Return a new VCMInscriptionModal object
 * @constructor
 */
function VCMInscriptionModal(page) {
	this._page = page;
	this._modal = page.getModal();
}

VCMInscriptionModal.prototype = {
	/**
	 * Reference to a VCMPage object
	 * @type {VCMPage}
	 */
	_page: null,
	
	/**
	 * Reference to a VCMModal object
	 * @type {VCMModal}
	 */
	_modal: null,
	
	/**
	 * jQuery reference to tabs label
	 * @type {jQuery}
	 */
	_tabs: null,
	
	/**
	 * jQuery reference to tabs container
	 * @type {jQuery}
	 */
	_tabsContainers: null,
	
	
	/**
	 * jQuery reference to left side
	 * @type jQuery
	 */
	_leftSide: null,
	
	/**
	 * jQuery reference to left arrow
	 * @type {jQuery}
	 */
	_leftArrow: null,
	
	/**
	 * jQuery reference to right side
	 * @type jQuery
	 */
	_rightSide: null,
	
	/**
	 * jQuery reference to right arrow
	 * @type {jQuery}
	 */
	_rightArrow: null,
	
	/**
	 * jQuery reference to close button
	 * @type {jQuery}
	 */
	_btnClose: null,
	
	/**
	 * jQuery reference to button confirm
	 * @type {jQuery}
	 */
	_btnConfirm: null,
	
	/**
	 * jQuery reference to button next
	 * @type {jQuery}
	 */
	_btnNext: null,
	
	/**
	 * jQuery reference to button previous
	 * @type {jQuery}
	 */
	_btnPrevious: null,
	
	/**
	 * jQuery reference to the use photo button
	 * @type {jQuery}
	 */
	_btnUsePhoto: null,
	
	/**
	 * Reference to the AjaxUpload
	 * @type {AjaxUpload}
	 */
	_ajaxUpload: null,
	
	/**
	 * Current active tab
	 * @type {Number}
	 */
	_currentTab: 0,
	
	/**
	 * jQuery reference to checkboxes representing all items
	 * @type {jQuery}
	 */
	_allCheckboxes: null,
	
	/**
	 * jQuery reference to checkboxes representing one item
	 * @type {jQuery}
	 */
	_oneCheckboxes: null,
	
	/**
	 * jQuery reference to states dropdown
	 * @type {jQuery}
	 */
	_jState: null,
	
	/**
	 * jQuery reference to countries dropdown
	 * @type {jQuery}
	 */
	_jCountry: null,
	
	/**
	 * Data to associate a country with theirs states
	 * @type {Array}
	 */
	_statesCountries: [{
		country: 'CA',
		states: ['AB','BC','MB','NB','NL','NS','NT','NU','ON','PE','QC','SK','YT']	
	}, {
		country: 'US',
		states: ['AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','VI','WA','WV','WI','WY']
	}],
	
	/**
	 * jQuery reference to numerical fields
	 * @type {jQuery}
	 */
	_jNumFields: null,
	
	/**
	 * Initialize the inscription modal
	 */
	init: function(tab) {
		console.log('VCMInscriptionModal.init()');
		var me = this;
		$.get(VCMUtils.prepareCommand({command:'displayInscription'}), function(html) { me._init(html, tab); });
	},	
		
	_init: function(html, tab) {
		console.log('VCMInscriptionModal._init(', html, ')');
		this._modal.show(html);
		// Make jQuery reference to required elements
		this._tabs = $('#inscriptionTabs > li');
		this._tabsContainers = $('#inscriptionTabsContainer > div.inscriptionTab');
		this._leftSide = $('#inscriptionContent > .modalLeftSide');
		this._leftArrow = $('#inscriptionContent > .modalLeftSide > map > area');
		this._rightSide = $('#inscriptionContent > .modalRightSide');
		this._rightArrow = $('#inscriptionContent > .modalRightSide > map > area');
		this._btnClose = $('#inscriptionBtnClose');
		this._btnConfirm = $('#inscriptionBtnConfirm');
		this._btnNext = $('#inscriptionBtnNext');
		this._btnPrevious = $('#inscriptionBtnPrevious');
		this._btnUsePhoto = $('#photoUploadUse');
		this._btnUploadFilename = $('#photoUploadFilename');
		this._allCheckboxes = $("input[value=]:checkbox");
		this._oneCheckboxes = $("input[value!=]:checkbox");
		this._jState = $("select[name='state']");
		this._jCountry = $("select[name='country']");
		this._jNumFields = $('.inscriptionPhone > input');
		// Create Ajax Upload
		var me = this;
		this._ajaxUpload = new AjaxUpload('photoUploadButton', {
			action: rootPath + 'doJSON?command=uploadPhoto',
			name: 'photo',
			autoSubmit: false,
			responseType: 'json',
			onChange: function(file, ext) { return me.onFileChange(file, ext); },
			onComplete: function(file, response) { return me.onUploadComplete(file, response); }
		});
		// Select the specifyed tab
		if (tab !== undefined) {
			for(var i = 0; i < tab; i++) this.nextTab(true);
		}
		// Add events
		this.addEvents();
	},
	
	/**
	 * Destroy the inscription modal
	 */
	destroy: function() {
		console.log('VCMInscriptionModal.destroy()');
		// Remove events
		this.removeEvents();
		// Ajax Upload
		this._ajaxUpload = null;
		// Remove jQuery reference
		this._tabs = null;
		this._tabsContainers = null;
		this._leftArrow = null;
		this._rightArrow = null;
		this._btnClose = null;
		this._btnConfirm = null;
		this._btnNext = null;
		this._btnPrevious = null;
		this._btnUsePhoto = null;
		this._allCheckboxes = null;
		this._oneCheckboxes = null;
		this._jState = null;
		this._jCountry = null;
		this._jNumFields = null;
	},
	
	/**
	 * Add events
	 */
	addEvents: function() {
		console.log('VCMInscriptionModal.addEvents()');
		var me = this;
		this._leftArrow.click(function() { me.previousTab(); return false; });
		this._rightArrow.click(function() { me.nextTab(); return false; });
		this._btnClose.click(function() { me._modal.close(); return false; });
		this._btnConfirm.click(function() { me.sendForm(); return false; });
		this._btnPrevious.click(function() { me.previousTab(); return false; });
		this._btnNext.click(function() { me.nextTab(); return false; });
		this._btnUsePhoto.click(function() { me._ajaxUpload.submit(); return false; });
		this._allCheckboxes.click(function() { return me.onCheckboxClick($(this), true); });
		this._oneCheckboxes.click(function() { return me.onCheckboxClick($(this), false); });
		this._jState.change(function() { return me.onStateChange($(this)); });
		this._jCountry.change(function() { return me.onCountryChange($(this)); });
		this._jNumFields.keydown($.proxy(this, 'onNumFieldsKeyDown'));
	},
	
	/**
	 * Remove events
	 */
	removeEvents: function() {
		console.log('VCMInscriptionModal.removeEvents()');
		this._leftArrow.unbind('click');
		this._rightArrow.unbind('click');
		this._btnClose.unbind('click');
		this._btnConfirm.unbind('click');
		this._btnPrevious.unbind('click');
		this._btnNext.unbind('click');
		this._btnUsePhoto.unbind('click');
		this._allCheckboxes.unbind('click');
		this._oneCheckboxes.unbind('click');
		this._jState.unbind('change');
		this._jCountry.unbind('change');
		this._jNumFields.unbind('keypress')
	},

	/**
	 * On State change
	 * @param {jQuery} jSel
	 */
	onStateChange: function(jSel) {	
		var state = jSel.val();
		for(var i in this._statesCountries) {
			var sc = this._statesCountries[i];
			if ($.inArray(state, sc.states) >= 0) {
				this._jCountry.val(sc.country);
				break;
			}
		}
	},
	
	/**
	 * On country change
	 * @param {jQuery} jSel
	 */
	onCountryChange: function(jSel) {
		var ok = false;
		for(var i in this._statesCountries) {
			if (this._statesCountries[i].country == jSel.val()) {
				ok = true;
			}
		}
		if (!ok) {
			this._jState.val('XX');
		}
	},
	
	/**
	 * On checkbox click
	 * @param {jQuery} jChk
	 * @param {Object} all
	 */
	onCheckboxClick: function(jChk, all) {
		console.log('VCMInscriptionModal.onCheckboxClick(', jChk, all , ')');
		var sel = "input[name='" + jChk.attr('name') + "'][value" + (all ? '!' : '') + "=]";
		$(sel).attr('checked', null);
	},
	
	/**
	 * Method trigered when the file is changed
	 * @param {String} file
	 * @param {String} ext
	 */
	onFileChange: function(file, ext) {
		console.log('VCMInscriptionModal.onFileChange(', file, ext, ')');
		if (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)) {
			this._btnUploadFilename.html(file);
			this._btnUsePhoto.show();
		} else {
			// TODO Mettre l'erreur ailleurs
			this._btnUploadFilename.html('<span style="color:red;">Type de fichier incorrecte</span>');
			this._btnUsePhoto.hide();
		}
	},
	
	/**
	 * Method trigered when the upload is complete
	 * @param {String} file
	 * @param {String} response
	 */
	onUploadComplete: function(file, response) {
		console.log('VCMInscriptionModal.onUploadComplete(', file, response, ')');
		if (response.success) {
			$('.inscriptionPhoto > div > img').attr('src', response.msg + '?' + Math.random());
			$('input[name=urlPhoto]').val(response.msg.substring(response.msg.lastIndexOf('/') + 1));
		} else {
			this._btnUploadFilename.html('<span style="color:red;">' + response.msg + '</span>');
		}
		this._btnUsePhoto.hide();
	},
	
	/**
	 * Method called when switching to previous tab
	 */
	previousTab: function() {
		console.log('VCMInscriptionModal.previousTab()');
		
		this._tabs.removeClass('active');
		$(this._tabsContainers[this._currentTab]).hide();
		this._currentTab--;
		$(this._tabs[this._currentTab]).addClass('active');
		$(this._tabsContainers[this._currentTab]).show();
		
		if (this._currentTab == 0) {
			this._leftSide.removeClass('arrow');
			this._btnPrevious.hide();
		} else if (this._currentTab == 1) {
			this._btnConfirm.hide();
			this._btnNext.show();
		} else {
			this._leftSide.addClass('arrow');
			this._rightSide.addClass('arrow');
			this._btnPrevious.show();
		}
	},
	
	/**
	 * Method called when switching to next tab
	 * @param {Boolean,Null} formOk
	 */
	nextTab: function(formOk) {
		console.log('VCMInscriptionModal.nextTab()');
		if (formOk === undefined && this._currentTab == 0 && !this.verifyForm()) return;
		if (formOk === undefined && this._currentTab == 2 && !this.sendForm()) return;
		
		this._tabs.removeClass('active');
		$(this._tabsContainers[this._currentTab]).hide();
		this._currentTab++;
		$(this._tabs[this._currentTab]).addClass('active');
		$(this._tabsContainers[this._currentTab]).show();
		
		if (this._currentTab == 3) {
			this._leftSide.removeClass('arrow');
			this._rightSide.removeClass('arrow');
			this._btnPrevious.hide();
			this._btnConfirm.hide();
			this._btnClose.show();
		} else if (this._currentTab == 2) {
			this._btnNext.hide();
			this._btnConfirm.show();
		} else {
			this._leftSide.addClass('arrow');
			this._rightSide.addClass('arrow');
			this._btnPrevious.show();
		}
	},
	
	/**
	 * Verify the validity of the form
	 */
	verifyForm: function() {
		console.log('VCMInscriptionModal.verifyForm()');
		var formOk = true,
			me = this,
			ajax = 0;		
		// Vérifier le courriel
		var email = $('#inscriptionTabInfo input[name=email]').val();
		$('#inscriptionEmail > span').addClass('hidden');
		// Si le courriel est vide
		if (email.length == 0) {
			$('#inscriptionEmail > span.inscriptionErrorRequired').removeClass('hidden');
			formOk = false;
		}
		else if (/.+@.+\..+/.test(email) == false) {
			$('#inscriptionEmail > span.inscriptionErrorInvalid').removeClass('hidden');
			formOk = false;
		}
		else if ($('#inscriptionTabInfo input[name=email]').attr('disabled') == false) {
			ajax++;
			$.getJSON(rootPath + 'doJSON?command=checkEmailAvailability&email=' + email, function(data) {
				ajax--;
				if (data && !data.success) {
					$('#inscriptionEmail > span.inscriptionErrorExisting').removeClass('hidden');
					formOk = false;
				}
				if (formOk && ajax == 0) {
					me.nextTab(true);
				}
			});
		}
		// Vérifier le mot de passe
		var pass1 = $('#inscriptionTabInfo input[name=password]').val(),
			pass2 = $('#inscriptionTabInfo input[name=password2]').val();
		$('#inscriptionPassword > span').addClass('hidden');		
		if (pass1.length == 0 || pass2.length == 0) {
			$('#inscriptionPassword > span.inscriptionErrorRequired').removeClass('hidden');
			formOk = false;
		} else if (pass1 != pass2) {
			$('#inscriptionPassword > span.inscriptionErrorInvalid').removeClass('hidden');
			formOk = false;
		}
		// Vérifier le pseudo
		var username = $('#inscriptionTabInfo input[name=username]').val();
		$('#inscriptionUsername > span').addClass('hidden');
		if (username.length == 0) {
			$('#inscriptionUsername > span.inscriptionErrorRequired').removeClass('hidden');
		} else {
			ajax++;
			$.getJSON(rootPath + 'doJSON?command=checkUsernameAvailability&username=' + username, function(data) {
				ajax--;
				if (data && !data.success) {
					$('#inscriptionUsername > span.inscriptionErrorInvalid').removeClass('hidden');
					formOk = false;
				}
				if (formOk && ajax == 0) {
					me.nextTab(true);
				}
			});
		}
		return false;
	},
	
	/**
	 * Send to form
	 */
	sendForm: function() {
		console.log('VCMInscriptionModal.sendForm()');
		// Replace all checkbox
		if ($("input[name=disciplines][value=]").attr('checked')) {
			$("input[name=disciplines][value=]").attr('checked', false);
			$("input[name=disciplines][value!=]").attr('checked', true);
		}
		if ($("input[name=sectors][value=]").attr('checked')) {
			$("input[name=sectors][value=]").attr('checked', false);
			$("input[name=sectors][value!=]").attr('checked', true);
		}
		if ($("input[name=daysOfWeek][value=]").attr('checked')) {
			$("input[name=daysOfWeek][value=]").attr('checked', false);
			$("input[name=daysOfWeek][value!=]").attr('checked', true);
		}
		// If no checkbox checked, remove infolettre
		if ($("input[name=disciplines]:checked, input[name=sectors]:checked").length == 0) {
			$("input[name=infolettre]").attr('checked', false);
		}
		// If email field is disabled, enable it to send it
		$("input[name=email]").attr('disabled', false);
		
		var url = rootPath + 'doJSON?command=saveProfile&' + $('#inscriptionForm').serialize(),
			me = this;
		$.getJSON(url, function(data) {
			if (data && data.success) {
				$('#inscriptionConfirmationEmail').text(data.msg);
				if (me._tabs.length == 4) {
					me.nextTab(true);
				} else {
					me._modal.close();
					me._page.getSideBar().displayProfile(true);
				}
			} else {
				alert(data === null ? 'Erreur fatale. Aucune donnée retournée.' : data.msg);
			}
		});
		return false;
	},
	
	onNumFieldsKeyDown: function(evt) {
		console.log(evt.which);
		var key = evt.which;
		if ((!evt.ctrlKey && !evt.altKey && key >= 48 && key <= 57) ||
			(key >= 96 && key <= 105) ||
			key == 8 || key == 9 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46) {
			return;
		}
		return false;
	}
};


