
// setup the branches array

var branches = new Array();
//0 - address, 1 - postcode, 2 - lat, 3 - lon, 4 - link, 5 - GLatLng
branches["London"] = ['<h3>Branch Address</h3>Lakestar Media Ltd.<br />3rd Floor, MacLaren House,<br />Talbot Road<br />Manchester<br />M32 0FP', 53.45587, -2.29082];
branches["Manchester"] = ['<h3>Branch Address</h3>Lakestar Media Ltd.<br />Amadeus House<br /> Floral Street <br />Covent Garden<br />London<br />WC2E 9DP',  51.512098, -0.125195];

// setup other variables

var postcode;
var startLatLng;
var endLatLng;
var distance;
var geocoder = new google.maps.Geocoder();
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

/*
// initialise map display 
//
// result: none
*/
function initialize() {

// setup directions obj
    directionsDisplay = new google.maps.DirectionsRenderer();

// define start lat/long (not displayed)
   var start = new google.maps.LatLng(53.4765, -2.2389);
   
   
    $("#map").hide();
    $("#branch").hide();
    $("#directiones").hide();
	$("#alternate").hide();
	
// define map options
    var myOptions = {
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        },
        mapTypeControl: true,
        scaleControl: false,
        streetViewControl: false,
        center: start
    }

// call v3 map
    map = new google.maps.Map(document.getElementById("map"), myOptions);

// set directions display on map
    directionsDisplay.setMap(map);

    if (document.getElementById("postcode").value != '') {

        doSearchByPostcode();
    }

	return false;
}

/*
// search from given postcode and display results
//
// result: boolean false to stop form submission
*/
function doSearchByPostcode() {

    // fetch postcode value from form
    postcode = document.getElementById("postcode").value;


    // check postcode and show error if no match
    if (!regCheck(/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$/i, postcode) || postcode == "" || !postcode) {

		errorMessage();

        return false;
    }

	
    // call geocoder with postcode (or address)
    geocoder.geocode( { 'address': postcode}, function(results, status) {

    // check geocoder response
    if (status == google.maps.GeocoderStatus.OK) {

        // geocoder good response (postcode found) so set as start location
        startLatLng = results[0].geometry.location;

        // find nearest branch (by direct distances)
        nearestBranch = calcShortestDistance(startLatLng);

alternate(nearestBranch);
        
		calcDistance(nearestBranch);

    } else {
        errorMessage();
      }
    });

    return false;
}

/*
// display error message
//
// return: none
*/
function errorMessage() {
    // no valid postcode (or address) given, so hide previous and return error message

	
	
    $("#branch").hide();
    $("#directiones").hide();
    $("#map").hide();

    $("#message").html("<p>&bull; Please enter a valid postcode and then click <b>'Search'</b></p>");
    $("#message").show();    
}


/*
// calculate the sortest distance between all branches
//
// param: point startLatLong start point for given postcode
// return: array index for nearest branch (direct route)
*/
function calcShortestDistance(startLatLng) {

    var distance = 0;
    var minBranch = '';
    var minDistance = 9999999;

// loop through all branches
    for (i in branches) {

        // create point for branch
        endLatLng = new google.maps.LatLng(branches[i][1], branches[i][2]);

        // use google spherical calcs library to find direct distance
        distance = google.maps.geometry.spherical.computeDistanceBetween(startLatLng, endLatLng);

        // check if shortest distance
        if (distance < minDistance) {

            // shorter than previous, so store
            minDistance = distance;
            minBranch = i;
        }
    }

    return minBranch;
}
function regCheck(r, s)
{
//    regCheck(/needle/i, $haystack)

    var reg = new RegExp(r);

    if (s == null | typeof(s) == 'undefined') {
        s = "";
    }

    s = jQuery.trim(s);
    if (s.match(reg)) {
        return true;
    } else {
        return false;
    }
}

	function alternate(branch)
	{

//	alternate = branch=='Manchester' ? 'London' : 'Manchester';

		document.getElementById('otheroffice').innerHTML=branch;
			$("#alternate").show();
	
	}
	
	function calcDistance (nearestBranch ){

		// create point for nearest branch
        endLatLng = new google.maps.LatLng(branches[nearestBranch][1], branches[nearestBranch][2]);

        // setup route request
        var request = {
            origin: startLatLng,
            destination: endLatLng,
            region: 'gb',
            unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        // do route request and callback
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                // route return OK, so set for display
                directionsDisplay.setDirections(response);

                // get route details
                var nearestRoute = response.routes[0].legs[0];

                // create branch message and stats, then display

            
                $("#directiones").show();
                $("#error_message").hide();

                // create branch contact details, then display
                var contactDetails =  branches[nearestBranch][0].replace(/;/g, '<br />');

                $("#branch").html(contactDetails);
                $("#branch").show();

                // create branch directions
                var directionsSteps = "<h3>Directions:</h3><ul>";

                // loop through returned steps and add to list
                for (i = 0; i < nearestRoute.steps.length; i++){
                    directionsSteps = directionsSteps + "<li>" + nearestRoute.steps[i].instructions + "</li>";
                }

                // display branch directions
                $("#directiones").html(directionsSteps + "</ul>");
                $("#directiones").show();

                $("#map").show();
                $("#map").show();

                // resize the map now it is displayed
                google.maps.event.trigger(map, 'resize');

            }
        });

	}
	
	function findAlterDirection(){
	
		var alternate = document.getElementById('otheroffice').innerHTML;
			
		if(alternate == 'Manchester')
		{
			var test = 'London';
		}else
		{
			var test = 'Manchester';
		}

		document.getElementById('otheroffice').innerHTML=test;
				$("#alternate").show();
		calcDistance (test );
	
	}
	

