var resetval = '-1'
var activities;
var emailRegex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
var postalRegex = /^([ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy]\d)$/
var phoneRegex = /^([(]?[2-9]\d{2}[)]?[-| |.]?\d{3}[-| |.]?\d{4}((( x| ext)\d{1,5})|))*$/

function init() {
	if($$('.tab')) tab_init()
	if($$('form')) form_init()
	if($$('#exploration .sport')) exploration_init()
}

/* ========= */
/* = FORMS = */
/* ========= */

function form_init(){
	if($('resend-error-text')) $('resend-error-text').setStyle({'display':'none'})
	if($('activity-error-text')) $('activity-error-text').setStyle({'display':'none'})
	if($('contact-error-text')) $('contact-error-text').setStyle({'display':'none'})
	$$('form input').each(function(e) {
		if(e.type == "text"){
			label = e.previousSiblings()[0]
			label.setStyle({'display':'none'})
			Event.observe(e, 'focus', focus_field)
			Event.observe(e, 'blur', blur_field)
		}
	})
}

function focus_field(){
	label = this.previousSiblings()[0]
	if (this.value == label.innerHTML) {
			this.value = ""
	}
}

function blur_field(){
	field = this.id
	if($(field).value == ""){
		$(field).value = this.previousSiblings()[0].innerHTML
	}
}

// IE does not recognize disable attribute on select options
function checkDisabledOptions(elem)
{
	if (elem.lastSelected == null)
	{
		elem.lastSelected = 0;
	}
	if (elem.options[elem.options.selectedIndex].disabled)
	{
		elem.selectedIndex = elem.lastSelected;
	}
	else
	{
		elem.lastSelected = elem.options.selectedIndex;
	}

}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup)
{
    if($(el).type && $(el).type.toLowerCase() == 'radio')
    {
        var radioGroup = $(el).name;
        var el = $(el).form;
    }
    else if ($(el).tagName.toLowerCase() != 'form')
    {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    
    return (checked) ? $F(checked) : null;
}

/* ======== */
/* = TABS = */
/* ======== */

function tab_init(){	
	if(window.location.toString().indexOf("thankyou")==-1){
		$$('.tab').each(function(e){
			if(e.id != 'activityselect') e.hide()
		})
	}else{
		$$('.tab').each(function(e){
			if(e.id != 'summary') e.hide()
			$('resend').hide()
		})
	}
	
	$$('#activityselect select').each(function(e){
		Event.observe(e, 'change', check_selects)
	})
	
	$$('.tab_control').each(function(e){
		Event.observe(e, 'click', control_tabs)
		e.setStyle({'cursor':'pointer'})
	})
	
	activities = new Array();
	if($('registration')){
		activities = $('registration').getInputs('hidden').findAll(function(n){
			return n.name.startsWith('activity_id')
		})
	}
}

/* ============== */
/* = VALIDATION = */
/* ============== */

function collect_classes(first, second){ // to do: would be nice to generalize this for n classes
	return $$('.'+first).findAll(function(n){
		return n.hasClassName(second)
	})
}

function disable_group(first, second, isdisabled){
	collect_classes(first, second).each(function(e){
		e.disabled = isdisabled
	})
}

function group_is_reset(first, second){
	var numreset = collect_classes(first, second).findAll(function(n){return n.value == resetval}).length
	var total = collect_classes(first, second).length
	//alert("numreset: " + numreset + " total: " + total)
	return numreset == total
}

function check_selects(){
	checkDisabledOptions(this);
	/*var names = this.classNames.split(' ')
	if(names.indexOf)*/
	var first = this.hasClassName('cop') ? 'cop' : 'cardel'
	var firstalt = this.hasClassName('cop') ? 'cardel' : 'cop'
	var second = this.hasClassName('am') ? 'am' : 'pm'
	
	if(this.value != resetval){ // user has made a selection, i.e. cop am so disable cardel am
		this.setStyle({'color':'#910CA1'})
		
		disable_group(firstalt, second, true)
		
		var index = activities.pluck('alt').indexOf(this.id)
		//alert("index: " + index)
		if(index != -1){
			activities[index].value=""
			activities[index].className=""
			activities[index].alt=""
		}
		
		
		// has the user already selected three items?
		if(!activities.pluck('value').include("")){
			show_error('activity-error-text', 'You can only select 3 sports.')
			this.setStyle({'color':'#4c992e'})
			this.value = resetval
			if(group_is_reset(first, second)){
				disable_group(firstalt, second, false)
			}
		}else{
			// is the user selecting an activity of the same type?
			var to_add = this.descendants()[this.selectedIndex].classNames().entries()[0]
			//alert("values: " + activities.pluck('value'))
			//alert("classes: " + activities.pluck('class'))
			//alert("alts: " + activities.pluck('alt'))
        	
			if(!activities.pluck('className').include(to_add)){
				if(this.id == 'cop_3'){// special case for mountain biking
					// time overlap?
					if(activities.pluck('alt').include('cop_2') || activities.pluck('alt').include('cop_4')){
						show_error('activity-error-text', 'You cannot choose this sport as it overlaps with another. Please choose another one.')
						this.setStyle({'color':'#4c992e'})
						this.value = resetval
						if(group_is_reset(first, second)){
							disable_group(firstalt, second, false)
						}
					}else{
						// find first empty
						var empty = activities.find(function(n){
							return n.value==""
						})
						empty.value=this.value // to submit into DB
						empty.addClassName(to_add)
						//empty.class=to_add	// type of sport, can't choose duplicates
						empty.alt=this.id	// for resetting
						$('cop_2').disabled = true
						$('cop_4').disabled = true
					}	
				}else if(this.id == 'cop_6'){
					//time overlap?
					if(activities.pluck('alt').include('cop_5') || activities.pluck('alt').include('cop_7') || activities.pluck('alt').include('cop_8')){
						show_error('activity-error-text', 'You cannot choose this sport as it overlaps with another. Please choose another one.')
						this.setStyle({'color':'#4c992e'})
						this.value = resetval
						if(group_is_reset(first, second)){
							disable_group(firstalt, second, false)
						}
					}else{
						// find first empty
						var empty = activities.find(function(n){
							return n.value==""
						})
						empty.value=this.value // to submit into DB
						empty.addClassName(to_add)
						//empty.class=to_add	// type of sport, can't choose duplicates
						empty.alt=this.id	// for resetting
						$('cop_5').disabled = true
						$('cop_7').disabled = true
						$('cop_8').disabled = true
					}
				}else{
					// find first empty
					var empty = activities.find(function(n){
						return n.value==""
					})
					empty.value=this.value // to submit into DB
					empty.addClassName(to_add)
					//empty.class=to_add	// type of sport, can't choose duplicates
					empty.alt=this.id	// for resetting
				}
			}else{
				show_error('activity-error-text', 'You&rsquo;ve already selected this sport. Please choose another one.')
				this.setStyle({'color':'#4c992e'})
				this.value = resetval
				if(group_is_reset(first, second)){
					disable_group(firstalt, second, false)
				}
			}
		}		
	}else if (this.value != -1){ 
		this.setStyle({'color':'#4c992e'})
		
		// the user may have reset a selection or reset the group
		if(group_is_reset(first, second)){
			disable_group(firstalt, second, false)
		}
		// remove from list
		//alert("values: " + activities.pluck('alt') + " looking for " + this.id)
		var index = activities.pluck('alt').indexOf(this.id)
		//alert("index: " + index)
		activities[index].value=""
		activities[index].className=""
		activities[index].alt=""
		
		// special case for mountain biking
		if(this.id == 'cop_3'){
			$('cop_2').disabled = false
			$('cop_4').disabled = false
		}else if(this.id == 'cop_6'){
			$('cop_5').disabled = false
			$('cop_7').disabled = false
			$('cop_8').disabled = false
		}
	}
}

function show_error(errorbox, message){
	$(errorbox).innerHTML = "ERROR: Oops... " + message
	$(errorbox).show()
	Effect.Pulsate(errorbox, {pulses: 1});
}

function check_tab(tab_id){
	var success = true
	//alert(tab_id)
	switch(tab_id){
		case 'activityselect':
		var empty = activities.findAll(function(e){return e.value == ""}).length
		if(activities.findAll(function(e){return e.value == ""}).length == activities.length){
			show_error('activity-error-text', 'Please select a minimum of 1 sport.')
			success = false
		} else {
			if([$('child_firstname'), $('child_lastname'), $('child_age')].findAll(matches_label).length == 0){
				if($R(6,12).include($('child_age').value)){
					success = true
				}else{
					show_error('activity-error-text', 'Sorry, only kids ages 6-12 are eligible.')
					success = false
				}
				var gender = $RF('registration', 'child_gender'); 
				if(gender != 'M' && gender != 'F')
				{
					show_error('activity-error-text', 'Please select a gender.')
					success = false
				}else{
					success = true
				}
			}else{
				show_error('activity-error-text', 'Please fill in all required fields.')
				success = false
			}
		}
		break;
		case 'contactinfo':
		//alert([$('parent_name'), $('parent_address'), $('emerg_name'), $('emerg_phone'), $('emerg_rel'), $('parent_city'), $('parent_province'), $('parent_postal'), $('parent_email'), $('parent_emailagain')].findAll(matches_label).pluck('id'))
			//if($('parent_name').present() && $('parent_address').present() && $('parent_homephone').present() && $('parent_cellphone').present() && $('emerg_name').present() && $('emerg_phone').present() && $('emerg_rel').present()){
			if(([$('parent_name'), $('parent_address'), $('emerg_name'), $('emerg_phone'), $('emerg_rel'), $('parent_city'), $('parent_province'), $('parent_postal'), $('parent_email'), $('parent_emailagain')].findAll(matches_label).length == 0) && ([$('parent_homephone'), $('parent_cellphone')].findAll(matches_label).length <= 1)){
				if($('parent_email').getValue() == $('parent_emailagain').getValue()){
					if(!$('parent_email').getValue().match(emailRegex)){
						show_error('contact-error-text', 'Please enter a valid email address.')
						success = false
					}else{
						//alert( !( (matches_label($('parent_homephone')) || $('parent_homephone').getValue().match(phoneRegex)) && (matches_label($('parent_cellphone')) || $('parent_cellphone').getValue().match(phoneRegex)) && $('emerg_phone').getValue().match(phoneRegex) ) )
						if(!( (matches_label($('parent_homephone')) || $('parent_homephone').getValue().match(phoneRegex)) && (matches_label($('parent_cellphone')) || $('parent_cellphone').getValue().match(phoneRegex)) && $('emerg_phone').getValue().match(phoneRegex) ) ){
							show_error('contact-error-text', 'Please enter a valid phone number.')
							success = false
						}else{
							if($('accept').checked){
								success = true
								if(matches_label($('parent_homephone'))){ $('parent_homephone').value = ""}
								if(matches_label($('parent_cellphone'))){ $('parent_cellphone').value = ""}
								$('registration').submit()
							}else{
								show_error('contact-error-text', 'Please select the check box to confirm that you will sign a copy of the waiver when you attend All Sport One Day with your child.')
								success = false
							}
						}						
					}
				}else{
					show_error('contact-error-text', 'Please enter matching email addresses.')
					success = false
				}
			}else{
				show_error('contact-error-text', 'Please fill in all required fields.')
				success = false
			}
		break;
	}
	return success;
}

function control_tabs(){
	var tab = this.ancestors().find(function(e) {
	  return e.hasClassName('tab');
	})
	
	var success;
	if(!this.hasClassName('prev')){
		success = check_tab(tab.id) 
	}else{
		success = true
	}
	
	if(success){
		// assumes that tabs are sibling divs
		if(this.hasClassName('next')){
			tab.next().show()
		}else if(this.hasClassName('prev')){
			tab.previous().show()
		}
		tab.hide()
		if(tab.id == 'activityselect'){
			$('resend').hide()
		}else{
			$('resend').show()
		}
	}
}

function matches_label(e){
	return e.getValue()==e.previousSiblings()[0].innerHTML
}

function check_resend(){
	if([$('resend_firstname'), $('resend_lastname'), $('resend_email')].findAll(matches_label).length > 0){
		show_error('resend-error-text', 'Please fill in all required fields.')
	}else{
		if(!$('resend_email').getValue().match(emailRegex)){
			show_error('resend-error-text', 'Please enter a valid email address.')
		}else{
			$('reminder').submit()
		}
	}
}

function check_form(id){
	form = $(id)
	alert(form)
	/*	
	var emailRegex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
	var postalRegex = /^([ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy]\d)$/
	
	var error = false
	var missing = false
	
	$('error-text').setStyle({'display' : 'none'})
	form.getInputs('text').each(function(e){ e.setStyle({'border' : '1px solid #cccccc'})})
	$('province').setStyle({'color' : '#000000'})
	
	$('error-text').innerHTML = "&nbsp;"
	if(form.getInputs('text', 'firstname').first().value == "" || form.getInputs('text', 'firstname').first().value == undefined){
		form.getInputs('text', 'firstname').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	if(form.getInputs('text', 'lastname').first().value == "" || form.getInputs('text', 'lastname').first().value == undefined){
		form.getInputs('text', 'lastname').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	if(form.getInputs('text', 'street').first().value == "" || form.getInputs('text', 'street').first().value == undefined){
		
		form.getInputs('text', 'street').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	if(form.getInputs('text', 'city').first().value == "" || form.getInputs('text', 'city').first().value == undefined){
		form.getInputs('text', 'city').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	var province = $$('#province option').find(function(e){
	    return e.selected
	}).value
	
	if(province == "" || province == undefined){
		$('province').setStyle({'color' : '#d5222e'})
		missing = true
	}	
	
	if(form.getInputs('text', 'email').first().value == "" || form.getInputs('text', 'email').first().value == undefined){
		form.getInputs('text', 'email').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}else if(!(form.getInputs('text', 'email').first().value.match(emailRegex))){
		$('error-text').innerHTML += "Please enter a valid email address."
		form.getInputs('text', 'email').first().setStyle({'border' : '2px solid #d5222e'})
		error = true
	}
	
	if(form.getInputs('text', 'emailagain').first().value == "" || form.getInputs('text', 'emailagain').first().value == undefined){
		form.getInputs('text', 'emailagain').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}else{
		if(form.getInputs('text', 'email').first().value != form.getInputs('text', 'emailagain').first().value){
			$('error-text').innerHTML += 'Email addresses do not match'
			form.getInputs('text', 'email').first().setStyle({'border' : '2px solid #d5222e'})
			form.getInputs('text', 'emailagain').first().setStyle({'border' : '2px solid #d5222e'})
			error = true
		}
	}
	
	if(form.getInputs('text', 'brokerage').first().value == "" || form.getInputs('text', 'brokerage').first().value == undefined){
		form.getInputs('text', 'brokerage').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	if(form.getInputs('text', 'suggestion').first().value == "" || form.getInputs('text', 'suggestion').first().value == undefined){
		form.getInputs('text', 'suggestion').first().setStyle({'border' : '2px solid #d5222e'})
		missing = true
	}
	
	//Humans won't fill this in, spambots will
	if(form.getInputs('hidden', 'nospam').first().value){
		$('error-text').innerHTML += "Spambot validation failed."
		error = true
	}
	
	if(!error && !missing){*/
		form.submit()
	/*} else {
		if(missing){ $('error-text').innerHTML += "Please fill in information marked in red below." } 
		$('error-text').setStyle({'display' : 'block'})
	}*/
}

function exploration_init(){
	//if($$('#exploration .sport')) exploration_init()
	$$('#exploration .sport').each(function(e){
		new Effect.Opacity(e.select('.sport-title').first(), { from: 1, to: 0, duration: 0.1});
		Event.observe(e, 'mouseover', show_sport_title)
		Event.observe(e, 'mouseout', hide_sport_title)
		Event.observe(e, 'click', show_sport_popup)
	})
	
	$$('.sport-popup').each(function(e){
		e.hide()
	})
	
	$$('.sport-popup .close').each(function(e){
		Event.observe(e, 'click', hide_sport_popup)
	})
}

function show_sport_title(){
	new Effect.Opacity(this.select('.sport-title').first(), { from: 0, to: 1, duration: 0.5});
}

function hide_sport_title(){
	new Effect.Opacity(this.select('.sport-title').first(), { from: 1, to: 0, duration: 1});
}

function show_sport_popup(){
	id = this.select('.sport-title').first().innerHTML.gsub(' ', '-').toLowerCase()
	$('exploration').hide()
	$(id).show()
}

function hide_sport_popup(){
	this.ancestors()[1].hide()
	$('exploration').show()
}


document.observe('dom:loaded', init)