
// JavaScript Document
$(document).ready (function () {					 
    setUserLocation();
    plotLocation();
    changeRadius();
});

//Allows the radius of the search to be changed
function changeRadius ()
{
	
	if ($('#radius').length == 0) { return false; } //Check that the form exists
	
	$('#radius').bind('change', function () {
	
		$('#postcode_form').submit();
	
	});
	
	
}

//Sets the users location before submitting the form
function setUserLocation ()
{

    //if ($('#postcode_form').length == 0) { return false; } //Check that the form exists
	
	
	
    /*
	document.getElementById('postcode_form').onsubmit = function() { //Listen for the submission

		findUserLocation(); //Location the user
		
		if ($('#js_postcode').length == 0) 
		{ 
			return false; //Stop the form submitting
		}
		
		setTimeout(function() {   alert( 'here' );   } , 1500 + 1000);
		
    }*/
	
	
	$('#postcode_form').bind('submit', function() {
		
		findUserLocation(); //Location the user
		
		if ($('#js_postcode').length == 0) 
		{ 
			return false; //Stop the form submitting
		}
		else
		{
			if($('#longitude').val() != '')
			{
				return true;	
			}
			else
			{
				setTimeout(function() { submitform() } , 1000);
				return false;
			}
    	}
		
	});
}

function submitform ()
{
	$('#postcode_form').submit();
}



var markerManager = []; //Set the array to store the markers

var stockistHTML = '';

//Launches the map
function plotLocation ()
{

	if ($('#map_canvas').length == 0) { return false; } //Check the map canvas exists
	
        deleteOverlays();
        
	//Default map centre
	var lat  = 53.39263;
	var lng  = -2.586988;
	var zoom = 4;
	
	
	//Use the users location to centre the map
	if ($('#latitude').val() != '') {
		lat = $('#latitude').val();
		zoom = 8;
	}
	
	if ($('#longitude').val() != '') {
		lng = $('#longitude').val();
	}
	
	var latlng = new google.maps.LatLng(lat, lng) ; //Set the default centre
	
    var myOptions = {
      zoom: zoom,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }; //Set the options object for the map
	
    map = new google.maps.Map(document.getElementById("map_canvas"),
    						      myOptions); //Create the map; 
	
	var radius   = $('#radius').val(); //Get the radius for the searchs

	if ($('#latitude').val() != '' && $('#longitude').val() != '') { //Plot the users postcode on the map
	
            placeMarker (latlng, map, false, 'user.png');
	
	}
        stockistHTML = '';
        $('#stockists-wrap').html('<div class="maploading" ><img src="assets/images/maps/ajax-loader.gif" alt="loading" /><div>Loading your stockists</div></div>');
        
	//User the users location and radius search to find stockists
	$.ajax ({
		type: 'GET',
                dataType: 'json',
		url: $('base').attr('href') + 'stockists/index/get-stockists/radius/' + $('#radius').val() + '/lat/' + $('#latitude').val() + '/lng/' + $('#longitude').val() + '/',
		success: function (response) {
                    
			var stockists = eval ( response ); //Get the JSON object returned from the AJAX
                        
			if (stockists.length > 0) { //Are there stockists to display
                        
				for(var i=0; i<stockists.length; i++) { //Loop through the stockists
                                    
					var latlng = new google.maps.LatLng(stockists[i]['latitude'], stockists[i]['longitude']) ; //Set the default centre
					
					//Build the content for the info window
					var infoContent = '<p><strong>' + stockists[i]['trading_name'] + '</strong></p>';
					
					var address ='';
					
					if (stockists[i]['address_1'] != '') {
						var address = stockists[i]['address_1'] + ',<br />';
					}
					
					if (stockists[i]['address_2'] != '') {
						address += stockists[i]['address_2']
					}
					
					if (stockists[i]['address_3'] != '') {
						address += stockists[i]['address_3']
					}
					
					if (stockists[i]['town'] != '') {
						address += stockists[i]['town'] + ',<br />';
					}
					
					if (stockists[i]['county'] != '') {
						address += stockists[i]['county'] + ',<br />';
					}
					
					if (stockists[i]['postcode'] != '') {					
						address += stockists[i]['postcode'] + ',<br />';
					}
					
					infoContent    += '<p>' + address + '</p>';
					
					if (stockists[i]['telephone_number'] != '') {
						infoContent  += '<p><strong>Telephone</strong>: ' + stockists[i]['telephone_number'] + '</p>';
					}
					
					if (stockists[i]['fax_number'] != '') {
						infoContent  += '<p><strong>Fax</strong>: ' + stockists[i]['fax_number'] + '</p>';
					}
					
					if (stockists[i]['email_address'] != '') {
						infoContent  += '<p><strong>Email</strong>: <a href="mailto:' + stockists[i]['email_address'] + '">' + stockists[i]['email_address'] + '</a></p>';
					}
					
					if (stockists[i]['website_url'] != '') {
						infoContent  += '<p><strong>Website</strong>: <a href="' + stockists[i]['website_url'] + '">' + stockists[i]['website_url'] + '</a></p>';
					}
					
					if (stockists[i]['distance'] != '') {
						infoContent  += '<p><strong>Distance from you </strong>: ' + stockists[i]['distance'] + ' miles</p>';
					}
                            
                                        
                                            stockistHTML += '<tr><td class="tdleftcol" ><h3>'+stockists[i]['trading_name']+'</h3><p>';
                                                if ( stockists[i]['address_1'] ) { stockistHTML += stockists[i]['address_1']; }
                                                if ( stockists[i]['address_2'] ) { stockistHTML += ', ' + stockists[i]['address_2']; }
                                                if ( stockists[i]['address_3'] ) { stockistHTML += ', ' + stockists[i]['address_3']; }
												
												if ( stockists[i]['address_3'] && stockists[i]['town'] )  { stockistHTML += ', ' }
												
                                                if ( stockists[i]['town'] ) { stockistHTML += stockists[i]['town']; }
                                                
												if ( stockists[i]['county'] ) { stockistHTML += ', ' + stockists[i]['county']; }
                                                if ( stockists[i]['postcode'] ) { stockistHTML += ', ' + stockists[i]['postcode']; }
                                            
											stockistHTML += '</td>';
											stockistHTML += '<td class="tdrightcol" >';
										
											
                                            if ( stockists[i]['telephone_number'] ) {
                                            stockistHTML += '<p>Tel: ' + stockists[i]['telephone_number'] + '</p>';
                                            }

                                            if ( stockists[i]['fax_number'] ) {
                                            stockistHTML += '<p>Fax: ' + stockists[i]['fax_number'] + '</p>';
                                            }

                                            if ( stockists[i]['website_url'] ) {
                                            stockistHTML += '<p>Website: <a href="'+stockists[i]['website_url'] + '">'+stockists[i]['website_url'] + '</a></p>';
                                            }

                                            if ( stockists[i]['email_address'] ) {
                                            stockistHTML += '<p>Email: <a href="mailto:'+stockists[i]['email_address'] + '">'+stockists[i]['email_address'] + '</a></p>';
                                            }
                                        stockistHTML += '</td></tr>';
					
					placeMarker(latlng, map, true, 'stockist.png', infoContent); //Place the marker on the map
                                      
                                        
				}
                                
                $('#stockists-wrap').html('<h2>Search Results</h2><div class="divider"></div><table id="resulttable" cellspacing="10px" ><thead><tr><th></th><th></th></tr></thead><tbody>'+stockistHTML+'</tbody><tfoot><tr><th></th><th></th></tr></tfoot></table>');
				
				
				var clusterOptions = {
					styles: [{
						url: 'assets/images/maps/cluster.png',
						height: 35,
				        width: 35,
						color: '#ffffff'
					  }]
				};
				
				var clusterer = new MarkerClusterer(map, markerManager, clusterOptions); //Add the markers to the cluster
				
				
				$('#resulttable').dataTable( {
					"sPaginationType": "full_numbers",
					"bLengthChange": false,
					"bFilter": true,
					"bSort": false,
					"bInfo": false,
					"bAutoWidth": false
		
				} );
				
				
			} else {
                            
                            $('#stockists-wrap').html('<p>There are no stockists found in this area.</p>');
                            
                        }
			
		}
	});

}

function populateStockists ()
{
   
   $('#stockists-wrap').html(stockistHTML); 
    
}

//Get the co-ordinates of the users postcode and plot
function plotPostcode ()
{
	
	geocoder = new google.maps.Geocoder(); //Get Google Geocoder
		
	geocoder.geocode( { 'address': $('#postcode').val(),
                            'region:': 'GB'}, function(results, status) { //Pass the postcode in to the geocoder and get coordinates

		if (status == google.maps.GeocoderStatus.OK) { //Location was found
			placeMarker(results[0].geometry.location, map, false, 'user.png'); //Put the marker on the map
			var cleanCoOrds = cleanLatLng(String(results[0].geometry.location)); //Clean co-ordinates up
			plotMarkerLocation(cleanCoOrds); //Update the hidden fields
		}
	
	});

}
//Similar to plotPostcode, but doesn't plot the map point and re-sumits the postcode form
function findUserLocation ()
{
	
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': $('#postcode').val(),
                            'region': 'GB'}, function(results, status) {

		if (status == google.maps.GeocoderStatus.OK) {			
			var cleanCoOrds = cleanLatLng(String(results[0].geometry.location));
			plotMarkerLocation(cleanCoOrds);
		}
	
	});
	
}

//Add a marker to the map
function placeMarker (latLng, map, cluster, iconImage, infoContent)
{
	
	infoContent = typeof(infoContent) != 'undefined' ? infoContent : ''; //If the infoContent hasn't been passed, set empty string
	
	//Set the marker options
	var markerOptions = {
		position: latLng,
		map: map,
		draggable: false,
		icon: $('base').attr('href') + 'assets/images/maps/' + iconImage
	};
        
        
	
	var marker = new google.maps.Marker(markerOptions); //Add the marker to the map

	if (cluster === true) { //Do we want to cluster this point

		markerManager.push(marker); //Add new marker to array
		
		var infowindow = new google.maps.InfoWindow({ //Set the content for the info window
			content: infoContent
		});
	
		
		google.maps.event.addListener(marker, 'click', function() { //Add click listener on the marker
                        infowindow.open(map,marker);
		});
	
	}
	
}

//Removes the open and close brackets and splits the string on comma
function cleanLatLng(point) {

	if(point != '') { //Has a point been passed through

		var dirty_points = point.split(','); //Split the string in 2
		var clean_lat    = dirty_points[0].substring(1, dirty_points[0].length); //Remove open bracket at the start of the string
		var clean_long   = dirty_points[1].substring(1, (dirty_points[1].length-1)); //Remove the space from the start and close bracket at the end of the string
		
		var clean_point = new Array(); //Create an array to store the new points in
		clean_point [0]= clean_lat; //Set latitude
		clean_point [1]= clean_long; //Set longitude
		
		return clean_point; //Return the array of clean co-ordinates
	
	} else {
	
		console.log('Valid Co-Ordinates are required in cleanLatLng()');
	
	}

}

//Updates the form with the users location
function plotMarkerLocation (latLng)
{

    $('#latitude').val(latLng[0]);
    $('#longitude').val(latLng[1]);
    
    plotLocation();

}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
	
	if (markerManager) {
		
		for (i in markerManager) {
			
			markerManager[i].setMap(null);
			
		}
		
		markerManager.length = 0;
	}
	
}

