/**
 * Unobtrusive Scripting Package
 *
 * @package simon
 * @version 1.0
 * @license WTFPL 2.0, http://sam.zoy.org/wtfpl/
 * @copyright Copyleft (c) 2010
 */
var simon = {

	/**
	 * Library Configuration
	 *
	 * Configure JavaScript libraries used for DOM manipulation. The
	 * libraries are provided by the Google AJAX Libraries API.
	 *
	 * @return void
	 */
	version: '1.0',
	addons: {
		base: {
			name: 'jquery',
			version: '1'
		},
		maps: {
			name: 'maps',
			version: '3'
		}
	},

	map: function() {
		if (($('#container').hasClass('section-1-3')) && ($('#map').length > 0)) {
			google.load(simon.addons.maps.name, simon.addons.maps.version, {
				'other_params': 'sensor=false',
				'callback': function() {
					/* Append styles needed by Google Maps */
					$('#map').css({
						width: $('#map').width(),
						height: $('#map').height()
					});
					/* Initialize the map */
					var map = new google.maps.Map(document.getElementById('map'), {
						zoom: 16,
						center: new google.maps.LatLng(50.92205, 6.9598),
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						mapTypeControl: false,
						navigationControlOptions: {
							style: google.maps.NavigationControlStyle.SMALL,
							position: google.maps.ControlPosition.TOP_LEFT
						}
					});
					var geocoder = new google.maps.Geocoder();
					/* Parse hCard and position appropriate marker on the map */
					$('.vcard').each(function() {
						var hcard = {
							address: $(this).find('.street-address').text(),
							postalCode: $(this).find('.postal-code').text()
						};
						geocoder.geocode({
							address: hcard.address + ', ' + hcard.postalCode
						}, function(results, status) {
							if (status === google.maps.GeocoderStatus.OK) {
								var marker = new google.maps.Marker({
									map: map,
									position: results[0].geometry.location,
									title: 'Klicken Sie hier, um die Route zu uns zu berechnen…'
								});
								var infowindow = new google.maps.InfoWindow({
									content: 'Hier finden Sie den absolut besten Job! <a href="http://goo.gl/fyoW5" target="simon_external">Jetzt Route zu uns berechnen!</a>'
								});
								google.maps.event.addListener(marker, 'click', function() {
									infowindow.open(map, marker);
								});
							}
						});
					});
				}
			});
		}
	},

	form: {

		/**
		 * URL Converter
		 *
		 * Converts any input to a valid URL.
		 *
		 * @return void
		 */
		toURL: function(currentValue) {
			newValue = currentValue.toLowerCase();
			newValue = newValue.replace('ä', 'ae');
			newValue = newValue.replace('ö', 'oe');
			newValue = newValue.replace('ü', 'ue');
			newValue = newValue.replace('ß', 'ss');
			newValue = newValue.replace('(', '');
			newValue = newValue.replace(')', '');
			newValue = newValue.replace(/^(\s)+/g, '');
			newValue = newValue.replace(/(\s)+$/g, '');
			newValue = newValue.replace(/(\s)+/g, '-');
			newValue = newValue.replace(/\W/g, '-');
			newValue = newValue.replace(/-+/g, '-');
			$('#url').val(newValue);
		},

		/**
		 * Form Validation
		 *
		 * Add form validation to admin forms.
		 *
		 * @return boolean value determining if the form is valid
		 */
		check: function(currentForm) {
			var missingFields = '', check = true;
			if (currentForm === 'news') {
				titleValue = $('#title').val();
				contentValue = $('#text').val();
				if (titleValue === '' || contentValue === '') {
					missingFields = $('<div class="error">Die Felder „Titel“ und „Inhalt“ sind Pflichtfelder und müssen ausgefüllt werden!</div>').insertBefore('h1').bind({
						'click': function() {
							$(this).fadeOut('slow');
						}
					});
					window.scrollTo(0, 0);
					check = false;
				}
			}
			if (currentForm === 'jobs') {
				titleValue = $('#title').val();
				contentValue = $('#description').val();
				if (titleValue === '' || contentValue === '') {
					missingFields = $('<div class="error">Die Felder „Bezeichnung“ und „Beschreibung“ sind Pflichtfelder und müssen ausgefüllt werden!</div>').insertBefore('h1').bind({
						'click': function() {
							$(this).fadeOut('slow');
						}
					});
					window.scrollTo(0, 0);
					check = false;
				}
			}
			return check;
		}

	},

	toggleJobs: function() {
		$('.jobs.truncated .selected').show();
		$('.jobs.truncated a[rel=up]').text('Alle anzeigen…').bind({
			'click': function() {
				$(this).parents('ul').find('li').show();
				$(this).parent('li').remove();
				return false;
			}
		});
	},

	/**
	 * External Link Handling
	 *
	 * Open external links in a new window. Add a short description to
	 * the link's title attribute.
	 *
	 * @see  http://gist.github.com/373681
	 * @param props  Configuration object (see configs in function)
	 * @return void
	 */
	addExternalLinks: function(props) {
		// default configuration
		var config = {
			'scope': 'body', // scope for external link detection
			'target': 'external', // either false or string, makes use of the "target" attribute to support Firefox tab handling and Safari status bar info
			'class': '', // apply CSS classes to an external link
			'relation': 'external', // apply a relationship to an external link
			'title': 'Opens in new window' // link title to inform the user about an external link
		};
		// if any properties were supplied, apply them to the config object
		for (var key in props) {
			if (config.hasOwnProperty(key)) {
				config[key] = props[key];
			}
		}
		// get all links and apply the desired handling
		$('a[href*="//"]', config['scope']).each(function() {
			// add attributes and classes
			$(this).attr({
				'rel': ($(this).attr('rel')) ? $(this).attr('rel') + ' ' + config['relation'] : config['relation'],
				'title': ($(this).attr('title')) ? $(this).attr('title') + ' (' + config['title'] + ')' : config['title']
			});
			if (config['class'] !== '') $(this).addClass(config['class']);
			if (config['target']) {
				$(this).attr('target', config['target']);
			} else {
				$(this).live({
					'click': function() {
						// open a new window and set focus
						var external = window.open($(this).attr('href'), 'external');
						external.focus();
						// stop the link's default action
						return false;
					}
				});
			}
		});
	},

	/**
	 * Error Handling
	 *
	 * Remove error, success and other notices on click.
	 *
	 * @return void
	 */
	addErrorHandling: function() {
		$('.error , .success , .notice').each(function() {
			$(this).bind({
				'click': function() {
					$(this).fadeOut('slow', function() {
						$(this).remove();
					});
				}
			});
		});
	},

	/**
	 * Internal Initialization
	 *
	 * Function calls for enhancements, event bindings et al. This
	 * should be the only function ever called from Outer Space.
	 *
	 * @return void
	 */
	init: function() {
		simon.addErrorHandling();
		simon.addExternalLinks({
			'title': 'Öffnet in neuem Fenster'
		});
		simon.map();
	}

};

/**
 * Initialization
 *
 * Load JavaScript library from Google's CDN and initialize scripting
 * when the DOM is ready.
 *
 * @return void
 */
google.load(simon.addons.base.name, simon.addons.base.version);
google.setOnLoadCallback(simon.init);
