
// Round corners

Event.observe(window, 'load', function () {
	Try.these(function (){ Nifty('#content', 'medium'); });
	Try.these(function (){ Nifty('#link_to_clubs', 'medium'); });
	Try.these(function (){ Nifty('#link_to_start', 'medium'); });
});


// Custom JS validations

Validation.add('validate-postcode', 'Please enter your postcode.', function (v) {
     return Validation.get('IsEmpty').test(v) ||  /((?:A[BL]|B[ABDHLNRST]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[CHNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?| M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTWY]?|T[ADFNQRSW]|UB|W[ACDFNRSV]?|YO|ZE)\d(?:\d|[A-Z])?)\s*(\d[ABD-HJLN-UW-Z]{2})/i.test(v)
});

Validation.add('validate-password-confirm', 'Please retype your password, this is a required field', function (v) {
  return $F('pupil_password') == v;
});

function fireEvent(element, event){
  if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
  }
  else{
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
 }
}


// Dependencies between forms

function FormDependency() {
	// Conditions: Array of conditions. All of them must be true for the elements_to_show to actually show.
	// Condition: [control, value1, value2, ...]. Control with getValue() equal to any given valueX for the condition to be true.
	// Value: integer, string, array or regular expression.
	
	if (arguments.length == 3) {
		// control, condition values, elements to show
		var tmp = [arguments[0]]
		if (Object.isArray(arguments[1])) {
			tmp += arguments[1];
		}
		else {
			tmp.push(arguments[1]);
		}
		this.conditions = [tmp];
	}
	else if (arguments.length == 2) {
		// [[control, condition values], [control, condition values], ...], elements to show
		this.conditions = $A(arguments[0]);
	}
	else {
		throw "The FormDependency contructor method must receive either 2 or 3 arguments";
	}
	
	this.elements_to_show = $$(arguments[arguments.length-1]);
	
	this.conditions.each(function (c) {
		$(c[0]).observe('change', this.check_dependencies.bind(this));
		this.check_dependencies();
	}.bind(this));
}

FormDependency.prototype.check_dependencies = function() {
	var make_visible = true;
	
	this.conditions.each(function (c) {
		var control = $(c[0]);
		var values = $A(c.slice(1, c.length));
		var partial_result = false;
		values.each(function (v) {
			if ( ! partial_result &&
					(v.call && v(control.getValue()) || control.getValue() == v)) {
				partial_result = true;
			}
		}.bind(this));
		make_visible = make_visible && partial_result;
	}.bind(this));

	if (make_visible) {
		this.elements_to_show.each(function (e) { $(e).show(); })
	}
	else {
		this.elements_to_show.each(function (e) { $(e).hide(); })
	}
}


// Show sports backgrounds on instincts page

function Instincts() {
}

Instincts.setup_background_text = function(link_id, sport_name, background_text) {
	var sport_url = $(link_id).readAttribute('href');
	var sport_id = sport_url.split('/').pop();
	var sport_background_url = sport_url + '?part=background';
	var tooltip_text = background_text + '<p class="read_more"><a href="' + sport_url + '" onclick="return Popup.open({url:this.href, width: 800, height: 600});">Read more &raquo;</a></p>'
	var tooltip_class_name = link_id + ' tooltip';

	new Tip(link_id, tooltip_text, {
		title: sport_name,
		showOn: 'click',
		hideOn: 'close',
		style: 'creamy',
		stem: 'rightTop',
		hook: { tip: 'rightTop' },
		offset: { x: -5, y: 5 },
		className: tooltip_class_name,
		closeButton: true,
		fixed: true
	});
	
	$(link_id).observe('click', function (event) {Event.stop(event);});
}

Instincts.start = function(sports_base_url) {
	// Image togglers
	$$('.category_images').each(function (set) {
		var large_image = $(set).select('.category_image_large img')[0];
		$(set).select('.category_images_small img').each(function (thumbnail) {
			Instincts.setup_thumbnail(thumbnail, large_image);
		});
	});
	
	// More tooltip setup
	document.observe('prototip:shown', function (event) {
		var shown_id = event.element().id;
		$$('.prototip').each(function (element) {
			var the_boxes = element.select('.' + shown_id);
			var the_box = (the_boxes.size() > 0 && the_boxes[0])
			if ( ! the_box) {
				element.hide();
			}
		});
	});
}

Instincts.setup_thumbnail = function (thumbnail, image) {
	$(thumbnail).observe('mouseover', function () {
		var thumb_src = $(thumbnail).readAttribute('src');
		var image_new_src = thumb_src.gsub('/small/', '/large/');
		$(image).writeAttribute('src', image_new_src)
	});
}

// Popup window, ripped off from http://jehiah.cz/archive/prototype-powered-popup-script

var Popup = {
  open: function(options) {
    this.options = {
      url: '#',
      width: 800,
      height: 600,
      name:"_blank",
      location:"no",
      menubar:"no",
      toolbar:"no",
      status:"yes",
      scrollbars:"yes",
      resizable:"yes",
      left:"",
      top:"",
      normal:false
    }
    Object.extend(this.options, options || {});

    if (this.options.normal) {
        this.options.menubar = "yes";
        this.options.status = "yes";
        this.options.toolbar = "yes";
        this.options.location = "yes";
    }

    this.options.width = this.options.width < screen.availWidth?this.options.width:screen.availWidth;
    this.options.height=this.options.height < screen.availHeight?this.options.height:screen.availHeight;
    var openoptions = 'width='+this.options.width+',height='+this.options.height+',location='+this.options.location+',menubar='+this.options.menubar+',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+',resizable='+this.options.resizable+',status='+this.options.status
    if (this.options.top!="")openoptions+=",top="+this.options.top;
    if (this.options.left!="")openoptions+=",left="+this.options.left;
    window.open(this.options.url, this.options.name,openoptions );
    return false;
  }
}


// Profile management

function Profile() {
}

Profile.start = function () {
	$('pupil_login').observe('keyup', Profile.check_login_uniqueness);
}

Profile.check_login_uniqueness = function () {
	var login = $F('pupil_login');
	if (this.previous && this.previous == login) {
		return;
	}
	this.previous = login;
	var messages = $$('.dupe-login');
	if (messages) {
		messages.each(function (p) { p.remove(); });
	}
	new Ajax.Request('/profile/login_exists/' + login, {
		onComplete: function (response) {
			var res = response.responseText;
			if (res == '1') {
				$('pupil_login').insert({after: '<div class="validation-advice dupe-login">This login name is already taken</div>'});
			}
		}
	});
}


// Asi questionnaire

function AsiQuestionnaire() {
}

AsiQuestionnaire.start = function () {
	$$('.sports_group').each(AsiQuestionnaire.enhance_sports_group);
}

AsiQuestionnaire.enhance_sports_group = function (group) {
	var sports = group.select('.grouped_sport');
	var i;
	for (i = 0; i < sports.length-1; i++) { // All but the last
		AsiQuestionnaire.add_enabler(sports[i], sports[i+1])
	}
}

AsiQuestionnaire.add_enabler = function (sport, enabled) {
	var p = $(document.createElement('p'));
	var field = sport.select('.field')[0];

	$(enabled).hide();
	field.appendChild(p);
	p.insert({bottom: '<a href="#">click to add another sport</a>'});
	p.select('a')[0].observe('click', function (event) {
		Event.stop(event);
		$(enabled).show();
		$(p).remove();
	})
}


// Asi results

function AsiResults() {
}

AsiResults.start = function () {
	var filter_container = 'q_results_filter';
	
	AsiResults.radios = $(filter_container).select('.radio');
	AsiResults.radios.each(function (r) {
		$(r).observe('click', AsiResults.filter);
	});

	AsiResults.list = $$('#ranked_list')[0];
	AsiResults.sports = $$('#ranked_list li');
	AsiResults.sports.each(Element.identify);
	
	AsiResults.sports_html = {};
	AsiResults.sports.each(function (s) {
		AsiResults.sports_html[s.id] = '<li id="' + s.id + '">' + s.innerHTML + '</li>';
	});
	
	AsiResults.filter();
	
	$(filter_container).select('.div_submit').each(Element.remove)
};


AsiResults.filter = function () {
	AsiResults.list.select('li').each(Element.remove);
	
	var to_hide = {};
	AsiResults.radios.each(function (r) {
		var value = $F(r);
		if ( ! value) {
			return;
		}
		
		var name = $(r).readAttribute('name');
		var filter_class_name = 'filter-' + name + '-' + value;
		
		AsiResults.sports.each(function (li) {
			if ($(li).select('.' + filter_class_name).size() == 0) {
				to_hide[li.id] = true;
			}
		});
	});

	AsiResults.sports.each(function (li) {
		if ( ! to_hide[li.id]) {
			AsiResults.list.insert({bottom: AsiResults.sports_html[li.id]});
		}
	});
}


// SortableTable

Try.these(function () {
	SortableTable.addSortType('asi-progress', function (a, b) {
		var calc = function(v) {
			var match = v.match(/^(\d+)/i);
			var value = match ? match[1]*1 : -1;
			return value;
		}
		return SortableTable.compare(a ? calc(a) : 0, b ? calc(b) : 0);
	});
	SortableTable.addSortType('asi-datetime', function (a, b) {
		var calc = function(v) {
			var match = v.match(/^(\d+)/i);
			var value = match ? match[1]*1 : -1;
			return value;
		}
		return SortableTable.compare(a ? calc(a) : 0, b ? calc(b) : 0);
	});

	SortableTable.addSortType('datetime', function (a, b) {
		var calc = function(v) {
			var r = v.match(/(\d\d?)(?:\/|-)(\d\d)(?:\/|-)(\d\d\d\d)\s*(?:(\d\d)\:(\d\d)(?:\:(\d\d))?\s?([a|p]?m?))?/i);
			var yr_num = r[3];
			var mo_num = r[2] * 1;
			var day_num = r[1];
			var hr_num = r[4] ? r[4] : 0;
			if(r[7] && r[7].toLowerCase().indexOf('p') != -1) {
				hr_num = parseInt(r[4]) + 12;
			}
			var min_num = r[5] ? r[5] : 0;
			var sec_num = r[6] ? r[6] : 0;
			return new Date(yr_num, mo_num, day_num, hr_num, min_num, sec_num, 0).valueOf();
		}
		return SortableTable.compare(a ? calc(a) : 0, b ? calc(b) : 0);
	});
});


// Clubs map

function ClubsMap() {
}

ClubsMap.init = function (container_map, container_div, lat, lng, base_callback_url) {
	google.load("maps", "2");
	ClubsMap.container_map = $(container_map);
	ClubsMap.container_div = $(container_div);
	ClubsMap.lat = lat;
	ClubsMap.lng = lng;
	ClubsMap.is_ready = false;
	ClubsMap.base_callback_url = base_callback_url;
}

ClubsMap.clubs = [];
ClubsMap.add_club = function (club_id, latitude, longitude, html_data, icon_url) {
	ClubsMap.clubs.push({
		id: club_id,
		lat: latitude,
		lng: longitude,
		html: html_data,
		icon: icon_url
	});
}

ClubsMap.start = function () {
	var GM = google.maps;
	var map = new GM.Map2(ClubsMap.container_map);
	var center = new GM.LatLng(ClubsMap.lat, ClubsMap.lng, 15);
	map.setCenter(center, 15);
	var bounds = map.getBounds();
	
	var base_icon = new GM.Icon();
    base_icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    base_icon.iconSize = new GSize(20, 34);
    base_icon.shadowSize = new GSize(37, 34);
    base_icon.iconAnchor = new GPoint(9, 34);
    base_icon.infoWindowAnchor = new GPoint(9, 2);
    base_icon.infoShadowAnchor = new GPoint(18, 25);
	
	ClubsMap.setup_fixed_position_device(ClubsMap.container_map, ClubsMap.container_div)
	
	$(ClubsMap.clubs).each(function (club) {
		var lat = club.lat;
		var lng = club.lng;
		var coords = new GM.LatLng(lat, lng);
		var marker_options = {};
		
		if (club.icon) {
			var marker_icon = new GM.Icon(base_icon);
			marker_icon.image = club.icon;
			//console.log(icon);
			marker_options = {icon: marker_icon}
		}
		var marker = new GM.Marker(coords, marker_options);

		map.addOverlay(marker);
		ClubsMap.setup_info_box(map, marker, club);

		// Add to the bounds both the coordinates of the marker and the coordinates
		// for an hypothetical marker located opposite. This is for the center of
		// the map to be kept in place upon setZoom() 
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		bounds.extend(coords);
		bounds.extend(new GM.LatLng(northEast.lat()-(northEast.lat() - lat)*2, northEast.lng()-(northEast.lng()-lng)*2));
	});
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.addControl(new GM.LargeMapControl());
	map.addControl(new GM.MapTypeControl());
	ClubsMap.is_ready = true;
}

ClubsMap.setup_fixed_position_device = function(container_map, container_div) {
	new PeriodicalExecuter(function () {
		var parent = $(container_map.parentNode);
		var parent_offset = parent.viewportOffset();
		var map_offset = container_map.viewportOffset();
		var map_bottom = container_map.cumulativeOffset().top + container_map.getHeight();
		var page_bottom = container_div.cumulativeOffset().top + container_div.getHeight();
		if (parent_offset.top < 0) {
			if (map_bottom < page_bottom || map_offset.top > 0) {
				parent.setStyle({paddingTop: -parent_offset.top + 'px'});
			}
		}
		else {
			parent.setStyle({paddingTop: 0});
		}
	}, 0.1);
}

ClubsMap.setup_info_box = function(map, marker, club) {
	var coordinates = marker.getLatLng(marker);
	google.maps.Event.addListener(marker, 'click', function () {
		ClubsMap.log_view(club.id);
		marker.openInfoWindowHtml(club.html);
		map.setCenter(coordinates, 15);
	});
	Event.observe(ClubsMap.find_club_link(club.id), 'click', function (e) {
		ClubsMap.log_view(club.id);
		marker.openInfoWindowHtml(club.html);
		map.setCenter(coordinates, 15);
		e.stop();
	});
}

ClubsMap.log_view = function(club_id) {
	new Ajax.Request(ClubsMap.base_callback_url + '/club_view/' + club_id);
}

ClubsMap.find_club_link = function(club_id) {
	return $('club-' + club_id);
}

ClubsMap.setup_legend_tooltip = function(element_id, title, content) {
	new Tip(element_id, content, {
		title: title,
		style: 'creamy',
		stem: 'rightTop',
		hook: { tip: 'rightTop' },
		offset: { x: -5, y: 5 },
		fixed: true,
		className: 'tooltip'
	});
}

ClubsMap.setup_nspcc_stuff = function(container, link, info) {
	var container = $(container);
	var link = $(link);
	var info = $(info);
	
	link.observe('click', function (event) {
		// sportObserving() doesn't seem to work on IE6,
		// so I'm using this flag instead
		if ( ! ClubsMap.nspcc_alert_shown) {
			ClubsMap.nspcc_alert_shown = true;
			ClubsMap.nspcc_info(container, link, info);
			new Ajax.Request(ClubsMap.base_callback_url + '/nspcc');
			new Effect.ScrollTo(container);
		}
	});
	container.hide();
}

ClubsMap.nspcc_info = function (container, link, info) {
	info.remove();
	Dialog.alert(info.innerHTML, {width:500, okLabel: "close"});
	container.show();
	ClubsMap.start();
}


// Physical report

function PhysicalReport() {
}

PhysicalReport.init = function () {
	PhysicalReport.create_common_report_unit();
	PhysicalReport.gather_reports();
	PhysicalReport.list_reports();
	PhysicalReport.setup_events();
	
	// Give IE6 enough time to put itself together
	Event.observe(window, 'load', function () {
		PhysicalReport.activate_option($$('.common_report_unit .column_text ul li')[0]);
	});
}

PhysicalReport.create_common_report_unit = function () {
	var export_link_html = $$('.report_unit .div_export')[0].innerHTML;
	$$('.report_unit')[0].insert({before: '<div class="report_unit common_report_unit"><div class="column_chart"></div><div class="column_text"></div><div style="clear: both;"></div><p class="div_export">' + export_link_html + '</p></div>'})
}

PhysicalReport.gather_reports = function () {
	PhysicalReport.reports = [];
	$$('.report_unit').each(function (unit) {
		if ( ! unit.hasClassName('common_report_unit')) {
			var task_name = unit.select('.task_name')[0].innerHTML;
			PhysicalReport.reports.push({
				name: task_name,
				elements: unit.select('.column_chart')[0].childElements()
			});
			unit.remove();
		}
	});
}

PhysicalReport.list_reports = function () {
	var base = $$('.common_report_unit .column_text')[0];
	var lis = [];
	PhysicalReport.reports.each(function (report) {
		lis.push('<li>' + report.name + '</li>')
	});
	base.insert({top: '<p>Physical tasks:</p><ul id="physical_tasks">' + lis.join('') + '</ul>'})
}

PhysicalReport.setup_events = function () {
	var lis = $$('.common_report_unit .column_text ul li');
	lis.each(function (li) {
		li.setStyle({cursor: 'pointer'});
		li.observe('click', function () { PhysicalReport.activate_option(li); });
	});
}

PhysicalReport.activate_option = function (node) {
	var task_name = node.innerHTML;
	var base = $$('.common_report_unit .column_chart')[0];
	base.childElements().each(function (node) { node.remove(); });
	Try.these(function () {base.select('h2')[0].remove();});
	PhysicalReport.reports.each(function (report) {
		if (report.name == task_name) {
			report.elements.each(function (node) { base.appendChild(node); });
		}
	});
	base.insert({top: '<h2>Distribution of results &ndash; ' + task_name + '</h2>'});
	
	$$('.common_report_unit .column_text ul li').each(function (li) {li.removeClassName('selected');});
	node.addClassName('selected');
}

// Class list

function ClassList() {}

ClassList.init = function () {
	$$('.secondary_row').each(Element.hide);
	
	$$('table.class_list').each(function (table) {
		table.observe('click', ClassList.table_clicked);
		table.observe('mouseover', ClassList.table_mouseover);
		table.observe('mouseout', ClassList.table_mouseout);
	});
}

ClassList.table_clicked = function(event) {
	var qrow = Event.findElement(event, 'tr');
	if ( ! ClassList.toggleable_row(qrow)) {
		return true;
	}

	var srow = qrow.next('.secondary_row');
	srow.toggle();
}

ClassList.table_mouseover = function(event) {
	var qrow = Event.findElement(event, 'tr');
	if ( ! ClassList.toggleable_row(qrow)) {
		return true;
	}

	qrow.addClassName('hover');
}

ClassList.table_mouseout = function(event) {
	var qrow = Event.findElement(event, 'tr');
	if ( ! ClassList.toggleable_row(qrow)) {
		return true;
	}

	qrow.removeClassName('hover');
}

ClassList.toggleable_row = function(row) {
	return row.hasClassName('quick_row') && ! row.hasClassName('unregistered')
}
