var map;
var accordion;
var open_accordion_item;
var mapcontroller;
var accordion_options = {};

window.addEvent('domready', function () {
		// Create a new mapcontroller so we can select office locations
		mapcontroller = new MapController('map', { location_url: 'get_office.php', location_info: 'office_info', jsonparser: parseOffice });
		
		// Show nice formatted hovers for the industry section images
		var tips = new FancyTips($$('.industryimage'), { fixed: false });

		// Preload big product images
		var images = [];
		$$('.thumbs').each(function (image) {
			var big_path = image.src.replace('thumb_', '');
			images.include(big_path);
		});
		
		// Preload industry hover images
		$$('.industry').each(function (industry) {
			var image = industry.getStyle('background-image');
			images.include(image.replace('url(', '').replace(')', ''));
		});
		
		// Preload all images defined above
		var preloader = new Asset.images(images);
		
		// Set up the news accordion if we are on the news page
		if ($('news')) {
			// Don't use the opacity effect on IE6, it messes up text display rather badly
			if (Browser.Engine.trident4) {
				accordion_options.opacity = false;
			}
			
			accordion = new Accordion('h3.atStart', 'div.atStart', accordion_options);
		}
});

function parseOffice(office)
{
	var html = '<p><strong>' + office.name + '</strong></p>';
	html += '<p>';
	
	html += office.address_1;
	if (office.address_2)
		html += ', ' + office.address_2;
	
	html += '<br />';
	
	html += office.city + ', ' + office.province + ', ' + office.country + '<br />';
	
	html += office.postcode + '<br />';
	
	if (office.phone)
		html += 'Tel: ' + office.phone + '<br />';
	
	if (office.fax)
		html += 'Fax: ' + office.fax + '<br />';
	
	if (office.email)
		html += '<a href="mailto:' + office.email + '">' + office.email + '<a>';
	
	html += '</p>';

	// Highlight the correct office
	$$('a[id^=office_]').removeClass('highlight');
	$('office_' + office.id).addClass('highlight');

	return html;
}

var MapController = new Class({

	Implements: [Options],

	options : {
		latitude: 'latitude',
		longitude: 'longitude',
		zoom: 'zoom',
		map_type: 'map_type',
		map_types: {},
		location_url: '',
		location_info: '',
		jsonparser: $empty
	},

	initialize: function (map_element, options)
	{
		if ($(map_element) && GBrowserIsCompatible()) {
			this.setOptions(options);

			// Set these options here to avoid errors if maps.js hasn't been included
			this.options.map_types = {
				'Map' : G_NORMAL_MAP,
				'Satellite' : G_SATELLITE_MAP,
				'Hybrid' : G_HYBRID_MAP
			};

			// Create a new Google Map
			this.map = new GMap2($(map_element));

			// Center the map around the latitude and longitude provided
			var point = new GLatLng($(this.options.latitude).value * 1, $(this.options.longitude).value * 1);
			this.map.setCenter(point, $(this.options.zoom).value * 1);
			
			// Create a new marker at the center of the map
			marker = new GMarker(point);
			this.map.addOverlay(marker);

			// Set the map type to the provided one, I.E. Map, Satellite or Hybrid
			this.setMapType($(this.options.map_type).value);

			// Add navigation, zoom and map type controls
			this.map.addControl(new GLargeMapControl());
			this.map.addControl(new GMapTypeControl());
		}
	},

	// Wrapper function so we can translate friendly strings to Google's map type constants
	// map_type should be one of 'Map', 'Satellite' or 'Hybrid'
	setMapType: function (map_type)
	{
		this.map.setMapType(this.options.map_types[map_type]);
	},

	// Request a new map location from the server.  The given url must return JSON data to be parsed
	// in the callback function, so change updateMap if this format changes
	//
	// location_id is the db id of the desired location
	setLocation: function (location_id)
	{
		var maprequest = new Request.JSON({url: this.options.location_url,
																																		method: 'get',
																														onComplete: this.updateMap.bind(this)})

		maprequest.send('id=' + location_id);
	},

	// Callback function for the location request.  Parses the returned JSON data and inserts it into
	// the page, and centers the map on the given latitude and longitude
	// The info is parsed using a callback function, jsonparser.  If this is not provided, the raw
	// json will be injected into the result element.
	//
	// NOTE: The return info must include the following properties:
	//		.latitude
	//		.longitude
	//		.map_type
	//		.map_zoom
	updateMap: function (location_info)
	{
		var html = location_info;

		// We can probably do better than outputting json straight to the client, so
		// check if a parser was defined
		if (this.options.jsonparser) {
			var html = this.options.jsonparser(location_info);
		}
		
		// Fill the provided element with our (hopefully) parsed info
		$(this.options.location_info).set('html', html);
		
		// Center the map around the returned latitude and longitude
		var point = new GLatLng(location_info.latitude * 1, location_info.longitude * 1);
		this.map.setCenter(point, location_info.map_zoom * 1);
			
		// Add a marker at the map center - YOU ARE HERE
		var marker = new GMarker(point);
		this.map.addOverlay(marker);

		// Change the map type to the one provided in the response
		this.setMapType(location_info.map_type);
	}
});

function setFormError(id, message)
{
	if ($(id + '_error'))
		$(id + '_error').remove();
	
	$(id + '_label').set('html', $(id + '_label').get('html') + '<strong id="' + id + '_error">' + message + '</strong>');
}

function validate_form(form_name)
{
	var valid = true;
	
	
	
	switch (form_name) {
		case 'frm_careers':
			var messages = new Hash({'name':'You have to provide your name',
																												'email':'You have to provide a valid email address',
																												'cv':'You have to attach your resume'});
																			
			messages.each(function(message, id) {

				if (!$(id).value) {
					setFormError(id, message);
					valid = false;
				}
				if ( id == "email " ) {
					if ( !$(id).value.isValidMail() ) {
						setFormError(id, message);
			 		valid = false;					
					}
				}
			});
		break;

		case 'frm_quote':
			var elements = ['name', 'company', 'country', 'phone', 'email', 'industry'];
			//document.forms['frm_quote'].getElements('span[id$=error]').setStyle('visibility', 'hidden');
			elements.each(function (id) {
				if (!$(id).value) {
					$(id + '_error').setStyle('visibility', 'visible');
					valid = false;
				}
			});
			if (!valid) {
				$('quote_form_error').setStyle('display', 'block');
			}
			break;
	}
	
	return valid;
}

function toggleCheckBoxes(value)
{
	var elements = ['state_1', 'state_2', 'state_3'];
	elements.each(function (id) {
			if ('state_' + value == id) {
				// Enable this element
				$(id).setStyle('display', 'block');
				$(id).disabled = '';
			} else {
				// Disabled this element
				$(id).setStyle('display', 'none');
				$(id).disabled = 'disabled';
			}
	});
	// This element is always disabled
	$('state_3').disabled = 'disabled';
}

// FancyTips, an (not quite) extension of mootools Tips
// Enables more formatting of the tip contents than what xhtml validation
// with Tips allows.
//
// Example HTML:
//
// <a href="link.html" class="tooltips">
//		Link text
//		<span class="tipcontents">
//			<img src="images/an_image.jpg" alt="An image" />
//			<strong>More formatting is allowed here</strong>
//		</span>
//	</a>
//
// Javascript:
//	
//	var my_tips = new FancyTips($$('.tooltips'));
//
var FancyTips = new Class({

	Implements: [Options],

	options : {
		tipcontents: '.tipcontents'
	},

	initialize: function (elements, options) {

		this.setOptions(options);

		// Set up the fancy tips by inserting the tip contents element
		// into the title attribute of the element that is to have the tooltip
		elements.each(function (element) {
			contents_element = element.getElement(this.options.tipcontents);
			if (contents_element) {
				element.set('title', contents_element.get('html'));
			}
		}, this);

		this.tips = new Tips(elements, options);
	}
});


String.implement({
	isValidMail: function ()
	{
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return filter.test(this);
	}
});


