(function ($, undefined) {
	$(window).load(function() {
		var locator_container = $('#locator')
		var directions_container = $('#locator_directions_container');
		
		if(locator_container.length > 0)
		{

			var default_points = {
					'122': [47.65711, 9.46964],
					'444': [49.015536, 2.178396],
					'1972': [41.1183, 28.635],
					'1897': [51.13540295044351, -0.03712177276611328],
					'2660': [44.123391, 9.910347],
					'449': [42.37636353113668, -83.26104640960693],
					'453':[1.31358, 103.679967],
					'454': [22.3693, 114.136885],
					'455': [18.622171091209946, 73.74675750732422],
					'456': [-6.283391678422748, 106.78333282470703],
					'457': [35.6811836, 139.7741539],
					'459': [23.709921, 90.407143],
					'2060': [-33.826541666666664, 18.510697222222223]
				};
				var search_data = $.parseJSON(tognumworldwide_search_data);

				// set default point relative to region
				if(search_data.region in default_points){
					var default_LatLng = new google.maps.LatLng(default_points[search_data.region][0], default_points[search_data.region][1]);
				}else{
					var default_LatLng = new google.maps.LatLng(47.65711, 9.46964);
				}
			
			// submit the form if the user hits the enter key on his keyboard
			locator_container.find('form#locator_form').keydown(
				function(e){
					// catch enter-key
					if( e.keyCode === 13) {
						e.preventDefault();
						e.stopPropagation();
						e.stopImmediatePropagation();
						this.submit(); // submit the form
						return;
					}
				}
			);

			// search
			
			
			// enhance form
			
			locator_container.find('.tabbed')
			.tabs({
				idPrefix:'locator_tab',
				create: function(){
					$(this).find('span').remove().end().find('ul').css('display', 'block');
				},
				select: function(event, ui) {
					if(ui.index == 1){
						$('#locator_address').val('');
					} else {
						$('#locator_dealer').val('');
					}
				}

			}).end()
			.find('#locator_form .formbuttons input')
			.replaceWith(
				(function () {
					var searchbutton = $('#locator_form .formbuttons #search_button');
					searchbutton.css('display','block');
					return searchbutton
					.click(
					       function(event){
							event.preventDefault();
							$('#locator_form').submit();
						}
					);
				})()
//				(function () {
//					return $('<a href="#"><img src="img/sales_service_btn.gif" width="154" height="16" alt="Search" /></a>')
//					.click(
//							function(event){
//								event.preventDefault();
//								$('#locator_form').submit();
//							}
//					);
//				})()
			);
			
			if($('#locator_dealer').hasClass('default_selected')){
				locator_container.find('.tabbed').tabs( "select" , 1 );
			} else {
				locator_container.find('.tabbed').tabs( "select" , 0 );
			}
			
			// map initialization
			var map = new google.maps.Map(
				locator_container.find('#locator_map').get(0),
				{
					zoom:12,
					center: default_LatLng,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					streetViewControl: false,
					mapTypeControl: false
				}
			);
			
			
			// add points & interaction
			var results = $('#locator_results>li');

			if(results.length > 0){
				var boundaries = new google.maps.LatLngBounds();
				
				// show circle if search was by radius
				if(search_data.radius > 0 && search_data.lat != '' && search_data.lng != ''){
					var circle = new google.maps.Circle({
						map:map,
						center:new google.maps.LatLng(search_data.lat, search_data.lng),
						radius: search_data.radius * 1000
					});
				}
				
				
				// entry <-> marker functionality
				results.each(function(){
					var $this = $(this);
					
					//find position
					if($this.find('.col>img').length){
						
						var LatLng = $this.find('.col>img').attr('alt').split(',');
					
						LatLng = new google.maps.LatLng(LatLng[0], LatLng[1]);
						
						//add to boundaries
						boundaries.extend(LatLng);
						
						//add marker
						google.maps.event.addListener(
							new google.maps.Marker({
								position: LatLng, 
								map: map
							}),
							'click',
							function() {
								// center map
								map.panTo(LatLng);
								map.setZoom(12);
								
								// scroll to & highlight list entry
								scrollToElement(
									$this,
									function(){
										$this.effect("highlight", {color:'#FEFCD1'}, 500);
									}
								);
								
							}.bind(this)
						);
						
						// click on small img
						$this.find('.col>img')
						.addClass('has-js')
						.click(
							function(){
								map.panTo(LatLng);
								map.setZoom(12);
								scrollToElement(locator_container);
							}
						).end()
					}
					//TODO: Replace href of directions link
				});
				
				if ( 1 == results.length ){
					var zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
			    	    if (this.getZoom()){
		        	    this.setZoom(11);
        				}
					    google.maps.event.removeListener(zoomChangeBoundsListener);
					});
				}
				
				// fit map to boundaries
				map.fitBounds(boundaries);
			}else{
				// display MTU Headquarter
				var default_marker = new google.maps.Marker({
					position: default_LatLng, 
					map: map, 
					title:"MTU Headquarter"
				 });   
			}
		}
		
		if(directions_container.length > 0){
			// initialize directions map
			
			var directionsService = new google.maps.DirectionsService();
			var directionsDisplay = new google.maps.DirectionsRenderer();
			var directionsUpdate = directions_container.find('#locator_directions_update');
			var directionsPanel = $('#locator_directions').get(0);
			var directionsDestination = directions_container.find('#locator_directions_qr img').attr('alt').split(',');
			directionsDestination = new google.maps.LatLng(directionsDestination[0], directionsDestination[1]);
			var directionsStart = directions_container.find('#locator_directions_start')
						.keydown(
							function(e){
								// catch enter-key
								if( e.keyCode === 13) {
									e.preventDefault();
									e.stopPropagation();
									e.stopImmediatePropagation();
									directionsUpdate.triggerHandler('click');
									return;
								}
							}
						);
			
			var directionsMap = new google.maps.Map(
				$('#locator_directions_map').get(0),
				{
					zoom:10,
					center: directionsDestination,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					streetViewControl: false,
					mapTypeControl: false
				}
			);
			
			// update directions
			directionsUpdate
			.click(
				function(event){
					event.preventDefault();
					setMapDirections(directionsStart.val(), directionsDestination);
				}
			);
		}
		
		
		function scrollToElement(el, duration, complete){
			if(el !== undefined){
				el = $(el);
				if(duration === undefined){
					duration = 500;
				}
				$('html, body').animate(
				{
					scrollTop: el.offset().top
				},
				duration,
				complete);
				
				return el;
			}
			return undefined;
		}
		
		function setMapDirections(start, stop){
			
			//clean up
			directionsDisplay.setMap(null);
			directionsDisplay.setPanel(null);
			directionsDisplay.setMap(directionsMap);
			directionsDisplay.setPanel(directionsPanel);
			
			if(start === undefined || start === ''){
				directionsDisplay.setMap(null);
				directionsDisplay.setPanel(null);
			}else{

				directionsService.route(
					{
						origin:start,
						destination:stop,
						travelMode: google.maps.DirectionsTravelMode.DRIVING
					},
					
					function(response, status) {
						if (status == google.maps.DirectionsStatus.OK) {
							directionsDisplay.setDirections(response);
						}else{
							alert($('#errortext_direction_not_found').html());
						}
					}
				);
			}
		}
	});	
})(window.jQuery);
