var geocoder;

var map;

var bounds;

var directionDisplay;

var directionsService;

var shops = [];

var ff = 'false';

$(document).ready(function(){

	if($('body.ie6').length == 1) {
		if(document.getElementById("map")) {
			$('#map').css('background','url(../img/map.gif) no-repeat');
		}
		return false;
	}
	
	if(document.getElementById("map")) {
	

		//If available 
		if (Modernizr.geolocation) {
			$('#myLoc').click(function() {
			//Find Pos
				if (navigator.geolocation) {
					console.log('supported');
					 navigator.geolocation.getCurrentPosition(success, error);
				} else {
					console.log('not supported');
				}
				return false;
			});
		} else {
			//hide button
			$('#myLoc').css('display','none');
		}
		$('#myLoc').css('display','none');

	//directions handler
	
	directionsDisplay = new google.maps.DirectionsRenderer();
	
	geocoder = new google.maps.Geocoder();
	
	var latlng = new google.maps.LatLng(51.461826,-2.510674);
	
	var myOptions = { 
		zoom: 13, 
		scrollwheel: false,
		disableDefaultUI: false, 
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP 
	};
	
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	
	//direction setup!
	
	directionsDisplay.setMap(map);
	
	//Create a new viewpoint bound
	
	bounds = new google.maps.LatLngBounds();
	
	
	//now we do something a bit different here..... if get was passed don't load them all but work out which is closest!
	
	var $_GET = getQueryParams(document.location.search);

	if ($_GET.location != undefined) {
		
		//add all the shops to a list first of all not the best method
		$('#postcode').val($_GET.location);		
				
		$('.shop').each(function(index) {
			
			var hcard = $(this);
			
			shops.push({'id':index,'lat':Number(hcard.find('.latitude').text()) ,'lng':Number(hcard.find('.longitude').text()) ,'postcode': hcard.find('.postal-code').text()});			
			
		});
				
		//now find the nearest!
		
		getNearest2(String($_GET.location));
		
		//addMakers();
	
	} else {
	
	
		addMakers();
	
	}
	
	//now wait!! put listerner on iinput box that I haven't done yet!
	
	$('#findStudioBig button#find').click(function() {
		
		getNearest($('#postcode').val());
		
		return false;
		
	});
	
	$('#findStudioBig button#reset').click(function() {
		//
		return false;
	
	});
	
	//
	$(window).bind('hashchange', function () { //detect hash change
        var hash = window.location.hash //hash to string (= "myanchor")
        $('li.studios').css('display','none');
	    $(hash).fadeIn('slow');
    });
	
	//Check for hash
	if (window.location.hash) {
		$('li.studios').css('display','none');
		var hash = window.location.hash;
		$(hash).css('display','block');
	} else {
		$('li.studios').css('display','none');
	}
	
	
	$('.listStudios a').click(function(event) {
		event.preventDefault();
		var value = $(this).attr('href');
		var withoutHash = value.substr(1);
		window.location.hash = value;
		 
		 
		$('li.studios').css('display','none');
	    $('#'+withoutHash).fadeIn('slow');
	    
	   
	    
	    return false;
	});
	
	}
});



function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {};
    var tokens;

    while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
			if (ft[0] == ji) {
				return ft[1];
			}
	}
}

function getNearest(postcode,add) {

	//get the lat lng on this location first!
	if (!geocoder) {
	
		return false;
	
	}
	
	var myLatLng = false;
	
	geocoder.geocode( 
			{'address': postcode + ',UK'},
			function(results, status) {
			
				if (status == google.maps.GeocoderStatus.OK) {
					
					myLatLng = results[0].geometry.location;
					
					//console.log(shops);
					
					for (var x = 0 ; x < shops.length; x++ ) {
					
						shops[x].distance = Number(
												getDistanceTo(
														{'lat': myLatLng.lat(),'lng': myLatLng.lng()},
														{'lat': Number(shops[x].lat),'lng': Number(shops[x].lng)}
														)
												);
					
					}
					
					
					//cycle shops again which is the shortest distance?
					
					var index = 0;
					
					var distance = 0;
					
					for (var x = 0 ; x < shops.length; x++ ) {
					
						if (shops[x].distance < distance || x == 0)	{
						
							index = shops[x].id;
							
							distance = shops[x].distance;
							
							var shopLatLng = new google.maps.LatLng(shops[x].lat,shops[x].lng);
							
						}
					
					}
					
					showShop(index,distance,myLatLng,shopLatLng,add);
					
				}  else {
				
					//error msg
					$error = $('<p class="error">Could not find town or city.</p>')
					$('#findStudioBig').append($error);
					
				}
				
			});
		
	
}


function getNearest2(postcode) {

	//get the lat lng on this location first!
	if (!geocoder) {
	
		return false;
	
	}
	
	var myLatLng = false;
	
	
	geocoder.geocode( 
			{'address': postcode + ',UK'},
			function(results, status) {
			
				if (status == google.maps.GeocoderStatus.OK) {
					
					myLatLng = results[0].geometry.location;
					
					//console.log(shops);
					
					for (var x = 0 ; x < shops.length; x++ ) {
					
						shops[x].distance = Number(getDistanceTo({'lat': myLatLng.lat(),'lng': myLatLng.lng()},shops[x]));
					
					}
					
					
					//cycle shops again which is the shortest distance?
					
					var index = 0;
					
					var distance = 0;
					
					for (var x = 0 ; x < shops.length; x++ ) {
					
						if (shops[x].distance < distance || x == 0)	{
						
							index = shops[x].id;
							
							distance = shops[x].distance;
							
							var shopLatLng = new google.maps.LatLng(shops[x].lat,shops[x].lng);
							
						}
					
					}
					
					
					var start = myLatLng;
					
					var end  = shopLatLng;
					//showShop(index,distance,myLatLng,shopLatLng,add);
					
					//load in the item
					
					directionsService = new google.maps.DirectionsService();
	
					var shop = $('.shop')[index];
					
					shop = $(shop);					
					
					var contentString = shop.find('.st').text();
					
					//get directions!?
					
					var request = {
						origin:start, 
						destination:end,
						travelMode: google.maps.DirectionsTravelMode.DRIVING
					};
					
					directionsService.route(request, function(result, status) {
						
						if (status == google.maps.DirectionsStatus.OK) {
						
							directionsDisplay.setDirections(result);
							directionsDisplay.suppressMarkers = true;
							//alert(result.DirectionsLeg);
							
							success(start);
							//event.preventDefault();
								
						  window.location.hash = '#'+contentString;
						 
							$('li.studios').css('display','none');
							$('#'+contentString).fadeIn('slow');
						
						}
					});
					
				}  else {
				
					//error msg
					$error = $('<p class="error">Could not find town or city.</p>')
					$('#findStudioBig').append($error);
					
				}
				
			});
		
	
}

function showShop(index,distance,start,end,marker) {
	
	//setup the direction service now!
					
	directionsService = new google.maps.DirectionsService();
	
	var shop = $('.shop')[index];
	
	shop = $(shop);
	
	//alert(shop.innerHTML);
	var str = shop.find('.street-address').text();
	var str = shop.find('.street-address').text();
	
	str += ',' + shop.find('.region').text();
	
	str += ',' + shop.find('.postal-code').text();
	
	str += ' is ' + distance + 'km  or ' + Number(distance/1.6).toPrecisionFixed(2) + ' Miles ?';
	
	var contentString = shop.find('.st').text();
	
	//get directions!?
	
	var request = {
    	origin:start, 
    	destination:end,
    	travelMode: google.maps.DirectionsTravelMode.DRIVING
 	};
 	
  	directionsService.route(request, function(result, status) {
    	
    	if (status == google.maps.DirectionsStatus.OK) {
      	
      		directionsDisplay.setDirections(result);
      		directionsDisplay.suppressMarkers = true;
      		//alert(result.DirectionsLeg);
      		
      		success(start);
      		event.preventDefault();
      			
		  window.location.hash = '#'+contentString;
		 
			$('li.studios').css('display','none');
	    	$('#'+contentString).fadeIn('slow');
    	
    	}
  	});
	
}

function addMakers() {
		
	var img = '/img/map-pins.png';

	//var img = '/img/icon_shop_marker.png';
	find = 'shop';
	
	var length = $('.'+find).length;
		
	$('.'+find).each(function(index) {
		
		var hcard = $(this);
	
		var address = hcard.find('.street-address').text();
		
		if (hcard.find('.extended-address').text() != '') address += ',' + hcard.find('.extended-address').text();
		
		if (hcard.find('.locality').text() != '')address += ',' +hcard.find('.locality').text();
		
		if (hcard.find('.region').text() != '') address += ',' +hcard.find('.region').text();

		var postcode = hcard.find('.postal-code').text();
				
		if (hcard.find('.latitude').text() != '' && hcard.find('.longitude').text() != '') {
			
			myLatLng = new google.maps.LatLng(hcard.find('.latitude').text(),hcard.find('.longitude').text());
			
			addMaker(myLatLng,index,hcard,img,length);
			
			
		} else if (geocoder) {
			geocoder.geocode( 
						{'address': address + ',' + postcode + ',UK'},
						function(results, status) {
							if (status == google.maps.GeocoderStatus.OK) {
								
								myLatLng = results[0].geometry.location;
								addMaker(myLatLng,index,hcard,img,length);			
								hcard.find('.latitude').text(myLatLng.lat());
								hcard.find('.longitude').text(myLatLng.lng());
								
							} else {
							
								geocoder.geocode( 
									{'address': hcard.find('.locality').text()  + ',' + postcode + ',UK'},
									function(results, status) {
										if (status == google.maps.GeocoderStatus.OK) {
								
											myLatLng = results[0].geometry.location;
											addMaker(myLatLng,index,hcard,img,length);						
											hcard.find('.latitude').text(myLatLng.lat());
											hcard.find('.longitude').text(myLatLng.lng());
									
										} 								
									});
							
							}
							
						});
						
		}
		
	});
		
}

var count = 0;

function loadUrl() {
	
	clearTimeout(timer);
	
	var $_GET = getQueryParams(document.location.search);

	//console.log($_GET.postcode);

	if (typeof($_GET.postcode) != null) {
		
		getNearest(String($_GET.postcode));
	
	}

}


function addMaker(myLatLng,index,hcard,img,length, you) {
	
	count++;
	
	shops.push({'id':index,'lat':myLatLng.lat(),'lng':myLatLng.lng(),'postcode': hcard.find('.postal-code').text()});
								
	//var contentString = '<p><strong>' + hcard.find('.org').text();
	//contentString += '<br/>' + address + '<br/>' + postcode;
	
	var contentString;// = '<p>';
	//contentString +=  hcard.text();
	//contentString += '</p>';
	contentString = hcard.find('.st').html();
	

	var infowindow = new google.maps.InfoWindow({
		content: contentString
	});
							
	var marker = new google.maps.Marker({
		position: myLatLng,
		map: map,
		animation: google.maps.Animation.DROP,
		title: hcard.find('.postal-code').text(),
		icon: img
		
	});
		
	//is that them all loaded?
	
	if (count == length ) {
	
		//load it!
		//console.log('ERE');
		//loadUrl();
	
	}
	
	//clearTimeout(timer);
	
	//timer = setInterval(loadUrl,duration);


	bounds.extend(myLatLng);
	map.fitBounds(bounds);
	
	if (you != false) {
	// Add click listener to toggle bounce
    google.maps.event.addListener(marker, 'click', function (event) {
     
		  window.location.hash = '#'+contentString;
		 
		$('li.studios').css('display','none');
	    $('#'+contentString).fadeIn('slow');
	    
	    $('html, body').animate({scrollTop:500}, 'slow');
	   
    });
    
    }


}

function toggleBounce(marker) {
    if (marker.getAnimation() != null) {
        marker.setAnimation(null);
    } else {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}




function getDistanceTo(latLng1,latLng2) {

	var R = 6371; //radius of earth if different value is required from standard 6,371km
	
	var precision = 2;
	
	var lat1 = latLng1.lat.toRad();
	var lon1 = latLng1.lng.toRad();
	
  	var lat2 = latLng2.lat.toRad();
  	var lon2 = latLng2.lng.toRad();
  	
  	var dLat = lat2 - lat1;
  	var dLon = lon2 - lon1;
  	
  	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1) * Math.cos(lat2) * 
          Math.sin(dLon/2) * Math.sin(dLon/2);
  
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  
  var d = R * c;
  
  return d.toPrecisionFixed(precision);

}


/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

/** 
 * Formats the significant digits of a number, using only fixed-point notation (no exponential)
 * 
 * @param   {Number} precision: Number of significant digits to appear in the returned string
 * @returns {String} A string representation of number which contains precision significant digits
 */
if (typeof(Number.prototype.toPrecisionFixed) === "undefined") {
  Number.prototype.toPrecisionFixed = function(precision) {
    if (isNaN(this)) return 'NaN';
    var numb = this < 0 ? -this : this;  // can't take log of -ve number...
    var sign = this < 0 ? '-' : '';
    
    if (numb == 0) { n = '0.'; while (precision--) n += '0'; return n };  // can't take log of zero
  
    var scale = Math.ceil(Math.log(numb)*Math.LOG10E);  // no of digits before decimal
    var n = String(Math.round(numb * Math.pow(10, precision-scale)));
    if (scale > 0) {  // add trailing zeros & insert decimal as required
      l = scale - n.length;
      while (l-- > 0) n = n + '0';
      if (scale < n.length) n = n.slice(0,scale) + '.' + n.slice(scale);
    } else {          // prefix decimal and leading zeros if required
      while (scale++ < 0) n = '0' + n;
      n = '0.' + n;
    }
    return sign + n;
  }
}

function success(position) {
	//console.log(position.coords.latitude + "," + position.coords.longitude);
	//var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	var img = '/img/you-pin.png';
	var hcard = $('#26B-Shaftesbury-Road');
	addMaker(position,100,hcard,img,30, false);
}

function error(msg) {
	console.log(msg);
  console.log(arguments);
}



