/*
Script: register.js
	Contains <AcademyRegistration>

Author:
	Alan Roemen <aroemen@aop.com>
	April 29, 2009

Class: AcademyRegistration

Requires:
	creditcard.js (required only if validating cc option is true)

Options:
	cost_enroll: (Int) Enrollment Cost. Default: 185
	cost_reenroll: (Int) Re-Enrollment Cost. Default: 100
	form_name: (String) Name of registration form element. Default: academy_reg
	validateCC: (Boolean) If true, validates credit card information passed in. Default: true
	baseURL: (Mixed) If false, the script will automatically find the http location of the script file.
	                 You can specify the location manually also.
*/

var AcademyRegistration = new Class({
	
	script_name: 'register.js',

	options: {
		cost_enroll: 185,
		cost_reenroll: 100,
		form_name: 'academy_reg',
		validateCC: true,
		baseURL: false,
		removeStudentPadding: 85,
		site: 'aoa',
		url: '/includes/inc.student-template.php'
	},

	initialize: function(options){
		//console.log('registration initialized');
		this.setOptions(options);
		this.base_url();
		this.form = $$('form[name=' + this.options.form_name + ']')[0];
		this.form.addEvent('submit', this.validate.bindWithEvent(this));
		if (this.form == '') return;
		this.student = $$('div.student')[0].clone();				
		this.student_dob($$('div.student').length );
		this.student.removeProperty('style');		
		/*this.student.getElements('input[type=text]').each(function(el){
			el.getParent().setHTML(el.getParent().innerHTML.replace(/value\=\".+?\"/, 'value=""'));
		});
		*/
		this.payment_info = $$('select[name=cc_type]').getLast() ? true : false;
		var rs = new Element('a', {
			'href': '#',
			'rel': 'remove_student',
			'class': 'remove-student'
		}).setHTML('Remove Student')
		if (this.options.removeStudentPadding !== false) rs.setStyle('padding-left', this.options.removeStudentPadding + 'px');	
		rs.injectAfter(this.student.getElement('h4'));
		$$('a[rel=remove_student]').each(function(el){
			el.addEvent('click', this.remove_student.bindWithEvent(this, el.getParent()));
		}.bind(this));

		if (this.payment_info){
			this.promo = this.form.getElement('input[name=key_code]');//$('key_code');
			this.promo_last = '';
			this.cost = this.form.getElement('input[name=amount_due]');//$('amount_due');
			this.discount = {'type': 'dollar', 'value': '0', 'products': []};
			this.invalid_promo = new Element('img', {
				'id': 'promo_image',
				'class': 'textfield',
				'src': '/images/register-error.png',
				'alt': 'Invalid Promotional Code',
				'title': 'Invalid Promotional Code',
				'styles': {
					'border': 'none',
					'width': '16px',
					'height': '16px'
				}
			});
			this.valid_promo = new Element('img', {
				'id': 'promo_image',
				'class': 'textfield',
				'src': '/images/register.gif',
				'styles': {
					'border': 'none',
					'width': '16px',
					'height': '16px'
				}
			});
			this.get_promotion();
		}

		$('add-student').addEvent('click', this.add_student.bindWithEvent(this));

		if (this.payment_info){
			$$('div.student input[type=radio]').addEvent('click', this.set_price.bindWithEvent(this));
			this.promo.addEvent('keyup', this.get_promotion.bindWithEvent(this));
		}
	},

  student_dob: function(a){
    var today = new Date();
		for ( i=1; i<=a; i++ ) {
			new MooDateSelect('ff_sdate_' + i, {
				dateFormat: 'F j, Y',
				todayName: false,
				closeName: 'Apply &amp; Close',
				defaultDate: new Date( today.getFullYear().toInt() - 14, today.getMonth(), today.getDate() ),
				stylesheet: 'scripts/datepicker/style.css',
			closeOnSelect: true
			});
		}
	},

	base_url: function(){
		if (this.options.baseURL !== false) return;
		var elements = document.getElementsByTagName('script');
		for (var i=0; i<elements.length; i++) {
			if (elements[i].src && (elements[i].src.indexOf(this.script_name) != -1)) {
				var src = elements[i].src;
				this.options.baseURL = src.substring(0, src.lastIndexOf('/'));
				break;
			}
		}
		// Get document base path
		var documentBasePath = document.location.href;
		if (documentBasePath.indexOf('?') != -1)
			documentBasePath = documentBasePath.substring(0, documentBasePath.indexOf('?'));
		documentBasePath = documentBasePath.substring(0, documentBasePath.lastIndexOf('/'));
		if (this.options.baseURL.indexOf('://') == -1 && this.options.baseURL.charAt(0) != '/')
			this.options.baseURL = documentBasePath + "/" + this.options.baseURL;
	},

	add_student: function(e){
		e = new Event(e).stop();
		var last = $$('div.student').pop();
		var count = $$('div.student').length + 1;
		var remove_student = this.remove_student;
		var student_dob = this.student_dob;
		
		// define student template
		new Ajax( this.options.url, {
			method: 'get',
			onComplete: function( response ){
				var el = new Element( 'div', {
					'class': 'student'
				}).setHTML( response );
				el.getElement('h4').removeProperty('style');
				el.getElement('h4').setHTML(el.getElement('h4').innerHTML.replace('Student Info: 1','Student Info:') + ' ' + count);
				el.setHTML(el.innerHTML.replace(/\_0/g, '_'+count).replace(/style="(.*)"/g,''));
				el.injectAfter(last);
				el.getElement('a[rel=remove_student]').addEvent('click', remove_student.bindWithEvent(this, el));
				$$('a[rel=remove_student]').setStyle('visibility', 'hidden');
				el.getElement('a[rel=remove_student]').setStyle('visibility', 'visible');
				new Element('div', {
					'class': 'clear',
					'styles': {
						'padding-top': '10px'
					}
				}).injectAfter(last);
				var date_field = $$('div.student input.dob]').pop();
				date_field.setProperty('id', 'ff_sdate_' + count);
				student_dob($$('div.student').length);
				
			}
		}).request();

		this.set_price();
		if (this.payment_info) el.addEvent('click', this.set_price.bindWithEvent(this));
		new Tips($$('.returnstudent_'+count), {
			className: 'promo',
			hideDelay: 800,
			fixed: true,
			offsets: {
				'x': 10,
				'y': -40
			}
		});
	},

	remove_student: function(e, el){
		e = new Event(e).stop();
		var el2 = el.getPrevious();
		el.remove();
		//el2.remove();

		var rs = $$('a[rel=remove_student]');
		var i = rs.length - 1;
		if (i >= 0) rs[i].setStyle('visibility', 'visible');

		this.set_price();
	},

	set_price: function(){
		if (!this.payment_info) return;
		var total_cost = 0;
		$$('div.student input[name^=student_]').each(function(el){
			if (!el.getProperty('name').match(/\_returning/)) return;
			if (!el.getProperty('checked')) return;

			var cost = 0;
			var enroll_fee = 0;
			var product = ''
			if (el.getProperty('value').toLowerCase() == 'no'){
				enroll_fee = this.options.cost_enroll;
				if (this.options.site=='aoa') product = 'AOAR';
				else if (this.options.site=='mga') product = 'GENR';
			} else {
				enroll_fee = this.options.cost_reenroll;
				if (this.options.site=='aoa') product = 'AOARR';
				else if (this.options.site=='mga') product = 'GENRR';
			}

			if (this.discount.products.indexOf(product) != -1){
				if (this.discount.type == 'dollar')
					cost = enroll_fee - this.discount.value;
				else if (this.discount.type == 'percent')
					cost = enroll_fee * ((100 - this.discount.value)/100);
				else cost = enroll_fee;
			} else cost = enroll_fee;
			total_cost += cost;
			this.form.getElement('input[name=student_' + el.getProperty('name').match(/\d+/)[0] + '_fee]').setProperty('value', cost.toFloat().toFixed(2));
		}.bind(this));

		this.cost.setProperty('value', '$ ' + total_cost.toFloat().toFixed(2));
	},

	get_promotion: function(e){
		var key_code = this.promo.getProperty('value');
		if (key_code.length == 0) {
			if ($('promo_image')) $('promo_image').remove();
			this.discount = {
				'type': 'dollar',
				'value': '0',
				'products': []
			};
			this.set_price();
			return;
		}
		if (key_code == this.promo_last) return;
		this.promo_last = key_code;
		if (key_code.length < 5) {
			if ($('promo_image')) $('promo_image').remove();
			(function(){if (!$('promo_image')) this.invalid_promo.injectAfter(this.promo);}.bind(this)).delay(500, this);
			this.discount = {
				'type': 'dollar',
				'value': '0',
				'products': []
			};
			this.set_price();
			return;
		}
		new Request({
			url: location.href,
			method: 'post',
			data: {
				'action': 'aopc_'+ this.options.site + '_registratio',
				'check_promo': key_code
			},
			onComplete: function(obj){
					obj = Json.evaluate(obj);
					if ($('promo_image')) $('promo_image').remove();
					if (obj.response.toLowerCase() != 'ok') {
						(function(){if (!$('promo_image')) this.invalid_promo.injectAfter(this.promo);}.bind(this)).delay(500, this);
						this.discount = {
							'type': 'dollar',
							'value': '0',
							'products': []
						};
						this.set_price();
						return;
					}
					this.discount = obj.discount;
					this.set_price();
					this.valid_promo.setProperties({
						'alt': obj.discount.description,
						'title': obj.discount.description
					});
					this.valid_promo.injectAfter(this.promo);
				}.bind(this)
		}).send();
	},

	validate: function(e){
		return true;
		e = new Event(e);
		if (!this.options.validateCC) return true;

		this.fields = {
			'cc_type': ['Card Type', 0, true],
			'cc_number': ['Card Number', 16, true],
			'cc_cid': ['Security Number', 3, true],
			'cc_exp_month': ['Expiration Month', 0, true],
			'cc_exp_year': ['Expiration Year', 0, true]
		}

		var goodtogo = true;
		var cardType = this.form.getElement('select[name=cc_type]').value;
		var cardNumber = this.form.getElement('input[name=cc_number]').value;
		var cardExpiration = this.form.getElement('select[name=cc_exp_month]').value + '/' + this.form.getElement('select[name=cc_exp_year]').value
		var cfields = this.form.getElements('select[name^=cc_]').merge(this.form.getElements('input[name^=cc_]'));
		cfields.each(function(field){
			name = field.getProperty('name');
			value = field.getProperty('value');
			if (value == '' || value.length < this.fields[name][1]){
				goodtogo = false;
				this.fields[name][2] = false;
			}
		}.bind(this));

		if (!checkCreditCard(cardNumber, cardType, cardExpiration) && ccErrorNo > 1){
			goodtogo = false;
			this.fields.cc_number[2] = false;
			this.fields.cc_number[3] = ccErrors[ccErrorNo];
		}

		if (goodtogo) return true;

		e.stop();
		this.show_error();
	},

	show_error: function(){
		this.error = {};
		this.background = new Element('div', {
			'styles': {
				'opacity': '0.7',
				'background-color': '#000000',
				'position': 'fixed',
				'top': '0',
				'left': '0',
				'z-index': '9998',
				'width': '100%',
				'height': '100%'
			}
		});
		this.wrapper = new Element('div', {
			'styles': {
				'position': 'fixed',
				'top': '50%',
				'left': '50%',
				'z-index': '9999',
				'width': '240px',
				'height': 'auto',
				'font': '11px Arial, Helvetica, sans-serif',
				'border': '10px solid #226bb6',
				'background-color': '#ffffff',
				'margin-top': '-100px',
				'margin-left': '-120px'

			}
		});
		this.error.title = new Element('div', {
			'styles': {
				'font-size': '12px',
				'font-weight': 'bold',
				'color': '#226bb6',
				'margin': '8px',
				'padding': '0'
			}
		}).setHTML('The following errors occurred:');
		this.error.body = new Element('div', {
			'styles': {
				'padding': '0',
				'margin': '8px'
			}
		});
		this.error.footer = new Element('div', {
			'styles': {
				'padding': '0',
				'margin': '8px'
			}
		});

		for (var i in this.fields){
			if (!this.fields[i][2])
				if (this.fields[i][3])
					this.error.body.setHTML(this.error.body.innerHTML + this.fields[i][3] + '<br />')
				else this.error.body.setHTML(this.error.body.innerHTML + this.fields[i][0] + ' is missing or invalid<br />');
		}

		new Element('img', {
			'src': this.options.baseURL + '/button_back.gif',
			'styles': {
				'margin-right': '10px',
				'cursor': 'pointer'
			},
			'events': {
				'click': function(){
					this.wrapper.remove();
					this.background.remove();
				}.bind(this)
			}
		}).injectInside(this.error.footer);

		this.error.title.injectInside(this.wrapper);
		this.error.body.injectInside(this.wrapper);
		this.error.footer.injectInside(this.wrapper);
		this.background.inject(document.body);
		this.wrapper.inject(document.body);
	}
});

AcademyRegistration.implement(new Options, new Events);
