﻿///<reference path="jquery-1.4.2-vsdoc.js"/>
//V3 integration below
//###################################################################

var geocoder;
var directionsService;
var myLatLng;
var myOptions;
var directionsDisplay;
var infowindow = null;

var map;
var markersArray = [];
var numberMarkersArray = [];
var boundsArray = [];

var directionsArray = [];

var latUpperBound;
var latLowerBound;
var lngUpperBound;
var lngLowerBound;

var southWest;
var northEast;

var lng;
var lat;

var geocodeLatLng;

var GoogleMaps = {
    Image: null
	, GetDirectionsBtn: null
	, FindStockistsBtn: null
	, PostcodeInput: null
	, RadiusDDL: null
	, UomDDL: null
	, IsDryEye: null
	, IsStockist: null
	, Init: function() {
	    var me = this;

	    me.Image = '/Resources/Global/Images/Maps/marker.png';

	    me.IsDryEye = $('.hidDes').val();
	    me.IsStockist = $('.hidStock').val();

	    geocoder = new google.maps.Geocoder();
	    directionsService = new google.maps.DirectionsService();

	    //me.CreateMap();

	    me.GetDirectionsBtn = $('#getDirections').click(function() {
	        me.GetDirections();
	        return false;
	    });

	    me.FindStockistsBtn = $('#findStockists').click(function() {
	        me.FindStockists($('#myPostcode').val());
	        return false;
	    });

	    me.PostcodeInput = $('#myPostcode').keyup(function() {
	        if ($('#myPostcode').val().length >= 4) {
	            me.FindStockists($('#myPostcode').val());
	        }
	    });

	    me.PostcodeInput = $('#myPostcode').keypress(function(e) {
	        var code = (e.keyCode ? e.keyCode : e.which);
	        if (code == 13) {
	            return false;
	        }
	    });

	    me.PostcodeInput = $('#myPostcode').blur(function() {
	        if ($('#myPostcode').val().length >= 4) {
	            me.FindStockists($('#myPostcode').val());
	        }
	    });

	    me.RadiusDDL = $('#radius').change(function() {
	        me.FindStockists($('#myPostcode').val());
	    });

	    /*me.UomDDL = $('#uom').change(function() {
	    me.FindStockists($('#myPostcode').val());
	    });*/

	    $('.dHide').click(function() {
	        me.HideDirections();
	    });

	    $('.a_gotoStockist').click(function() {
	        me.HideDirections();

	        me.ReCalcMap($(this).attr('rel'));
	        return false;
	    });

	    //$('.instructions').show();
	    $('.instrShow').hide();

	    $('.instrShow').click(function() {
	        me.ShowInstructions();
	        return false;
	    });

	    $('.instrHide').click(function() {
	        me.HideInstructions();
	        return false;
	    });

	    $('#map').css('height', '10px');

	    $('.noResults').hide();

	    $('.dirRow').css('display', 'none');

	    $('.getDir').live('click', function() {
	        me.SwitchToDirections($(this).attr('rel'));
	        return false;
	    });
	}

	, SwitchToDirections: function(postcodes) {
	    var me = this;

	    var splitter = postcodes.split(',');
	    var pcFrom = splitter[0];
	    var pcTo = splitter[1];

	    $('#from').val(pcFrom);
	    $('#to').val(pcTo);

	    $('#stockSearch .formWrapper').hide();
	    $('#findResults').hide();

	    $('#directions .formWrapper').show();
	}

	, CreateMap: function() {
	    var me = this;

	    myLatLng = new google.maps.LatLng(54.878051, -3.435973);

	    directionsDisplay = new google.maps.DirectionsRenderer();

	    myOptions = {
	        zoom: 5,
	        center: myLatLng,
	        mapTypeControl: true,
	        mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
	        mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
	    map = new google.maps.Map(document.getElementById("map"), myOptions);
	    directionsDisplay.setMap(map);
	    directionsDisplay.setPanel(document.getElementById("directions_panel"));

	    infowindow = new google.maps.InfoWindow({
	        content: "holding...",
	        maxWidth: 150
	    });

	    /*$.ajax({
	    dataType: "json",
	    url: '/Apps/Stockists/StockistsHandler.ashx',
	    data: {
	    f: 'list'
	    },
	    success: function(data, textStatus, XMLHttpRequest) {
	    if (data.success)
	    me.SetMarkers(map, data.d, me.Image);
	    },
	    error: function() {
	    alert('there was a problem retrieving the data');
	    }
	    });*/
	}

	, SetMarkers: function(map, stockists, image) {
	    var me = this;

	    me.ClearMarkers();

	    for (var i = 0; i < stockists.length; i++) {

	        var stockist = stockists[i];
	        var siteLatLng = new google.maps.LatLng(stockist.Lat, stockist.Lon);
	        var marker = new google.maps.Marker({
	            position: siteLatLng,
	            map: map,
	            icon: image,
	            title: stockist.Name,
	            zIndex: stockist.Order,
	            postcode: stockist.PostCode,
	            html: stockist.Html
	        });

	        markersArray.push(marker);

	        google.maps.event.addListener(marker, "click", function() {
	            //$('#to').val(this.postcode);
	            infowindow.setContent(this.html);
	            infowindow.open(map, this);
	        });
	    }
	}

	, SetNumberedMarkers: function(map, stockists, image) {
	    var me = this;

	    me.ClearNumberMarkers();

	    for (var i = 0; i < stockists.length; i++) {

	        var stockist = stockists[i];
	        var markerImage;
	        var markerTitle = stockist.Name;
	        if (stockist.DryEye && stockist.IsStockist) {
	            markerImage = '/Resources/Global/Images/Maps/sdm' + (i + 1) + '.png';
	            markerTitle += ' - Stockist and Dry Eye specialist'
	        } else if (stockist.DryEye) {
	            markerImage = '/Resources/Global/Images/Maps/dm' + (i + 1) + '.png';
	            markerTitle += ' - Dry Eye specialist'
	        } else {
	            markerImage = '/Resources/Global/Images/Maps/m' + (i + 1) + '.png';
	            markerTitle += ' - Stockist'
	        }
	        var siteLatLng = new google.maps.LatLng(stockist.Lat, stockist.Lon);
	        var marker = new google.maps.Marker({
	            position: siteLatLng,
	            map: map,
	            icon: markerImage,
	            title: markerTitle,
	            zIndex: (stockist.Order + 100),
	            postcode: stockist.PostCode,
	            html: stockist.Html
	        });

	        numberMarkersArray.push(marker);

	        google.maps.event.addListener(marker, "click", function() {
	            //$('#to').val(this.postcode);
	            infowindow.setContent(this.html);
	            infowindow.open(map, this);
	        });

	        // me.CheckBounds(stockist.Lat, stockist.Lon)
	    }

	    me.ZoomToshowAllMarkers();

	    /*console.log(numberMarkersArray.length == 1);

	    if (numberMarkersArray.length == 1) {
	    map.setZoom(15);
	    map.setCenter(siteLatLng);
	    }

	    if (!isNaN(latUpperBound) && !isNaN(latLowerBound) && !isNaN(lngUpperBound) && !isNaN(lngLowerBound)) {
	    //console.log(latUpperBound, latLowerBound, lngUpperBound, lngLowerBound);
	    southWest = new google.maps.LatLng(latUpperBound, lngLowerBound);
	    northEast = new google.maps.LatLng(latLowerBound, lngUpperBound);

	        var bounds = new google.maps.LatLngBounds(southWest, northEast)
	    //console.log(bounds);
	    map.fitBounds(bounds);
	    }*/
	}

	, CheckBounds: function(lat, lng) {
	    var me = this;

	    if (latUpperBound == null || latUpperBound < lat)
	        latUpperBound = lat;

	    if (latLowerBound == null || latLowerBound > lat)
	        latLowerBound = lat;

	    if (lngUpperBound == null || lngUpperBound < lng)
	        lngUpperBound = lng;

	    if (lngLowerBound == null || lngLowerBound > lng)
	        lngLowerBound = lng;
	}

	, ZoomToshowAllMarkers: function() {
	    var me = this;

	    var bounds = new google.maps.LatLngBounds();
	    //  Go through each...
	    //for (var i = 0, LtLgLen = markerList.length; i < LtLgLen; i++) {
	    var LtLgLen = numberMarkersArray.length;
	    for (var i = 0; i < LtLgLen; i++) {
	        var loc = numberMarkersArray[i];
	        //console.log(loc.position);
	        var l = loc.position.toString();
	        var latLngSplitter = l.split(",");
	        lat = latLngSplitter[0].replace("(", "");
	        lng = latLngSplitter[1].replace(")", "");
	        var myLatLng = new google.maps.LatLng(lat, lng);

	        //  And increase the bounds to take this point
	        //console.log(myLatLng);
	        bounds.extend(myLatLng);
	    }
	    //  Fit these bounds to the map
	    map.fitBounds(bounds);
	}

	, ClearMarkers: function() {
	    var me = this;

	    if (markersArray) {
	        for (i in markersArray) {
	            markersArray[i].setMap(null);
	        }
	        markersArray.length = 0;
	    }
	}

	, ClearNumberMarkers: function() {
	    var me = this;

	    if (numberMarkersArray) {
	        for (i in numberMarkersArray) {
	            numberMarkersArray[i].setMap(null);
	        }
	        numberMarkersArray.length = 0;
	    }
	}

	, GetDirections: function() {
	    var me = this;

	    var start = $('#from').val();
	    var end = $('#to').val();
	    var request = {
	        origin: start,
	        destination: end,
	        travelMode: google.maps.DirectionsTravelMode.DRIVING
	    };

	    if (start.length > 0 && end.length > 0) {

	        $('#map').animate({ width: '400px' }, 2000, function() {
	            directionsService.route(request, function(response, status) {
	                if (status == google.maps.DirectionsStatus.OK) {
	                    $('.directions').show();
	                    directionsDisplay.setDirections(response);
	                }
	            });
	        });

	        directionsArray.push(directionsDisplay);
	    }

	}


	, ClearDirections: function() {
	    var me = this;

	    if (directionsArray) {
	        for (i in directionsArray) {
	            directionsArray[i].setMap(null);
	        }
	        directionsArray.length = 0;
	    }
	}

	, HideDirections: function() {
	    var me = this;

	    me.ClearDirections();

	    $('.directions').hide(function() {
	        $('#map').animate({ width: '670px' }, 2000)
	    });
	}

	, HideInstructions: function() {
	    var me = this;

	    $('.instructions').hide();
	    $('.instrHide').hide();
	    $('.instrShow').show();
	}

	, ShowInstructions: function() {
	    var me = this;

	    $('.instructions').show();
	    $('.instrHide').show();
	    $('.instrShow').hide();
	}

	, FindStockists: function(postcode) {
	    var me = this;

	    me.HideDirections();

	    var radius = $('#radius').val();
	    //var uom = $('#uom').val();
	    var uom = 'm';

	    var all;

	    geocoder.geocode({ 'address': postcode }, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	            geocodeLatLng = results[0].geometry.location;
	        } else {
	            geocodeLatLng = '';
	        }
	    });

	    lat = 0;
	    lng = 0;

	    if (geocodeLatLng != '' && geocodeLatLng != undefined) {
	        var strGeoLatLng = geocodeLatLng.toString();

	        var latLngSplitter = strGeoLatLng.split(",");
	        lat = latLngSplitter[0].replace("(", "");
	        lng = latLngSplitter[1].replace(")", "");
	    }


	    // Currently commented out so that clicking the find stcokists button with an empty postcode returns the results not found
	    //if (postcode.length > 1) {

	    $.ajax({
	        dataType: "json",
	        url: '/Apps/Stockists/StockistsHandler.ashx',
	        data: {
	            f: 'findNearest',
	            lat: lat,
	            lng: lng,
	            radius: radius,
	            uom: uom,
	            des: me.IsDryEye,
	            stock: me.IsStockist
	        },
	        success: function(data, textStatus, XMLHttpRequest) {
	            if (data.success) {
	                if (data.d.length > 0) {
	                    me.CreateMap();
	                    me.HideInstructions();
	                    $('#findResults').css('margin-top', '20px');
	                    me.SetNumberedMarkers(map, data.d, me.Image);
	                    me.DisplaySearchResults(data.d);
	                } else {
	                    me.HideInstructions();
	                    $('#findResults').css('margin-top', '0px');
	                    me.DisplayNoResults();
	                }
	            }
	        },
	        error: function() {
	            alert('there was a problem retrieving the data');
	        }
	    });
	    //}
	}

	, ReCalcMap: function(latlng) {
	    var me = this;

	    var splitter = latlng.split(',');
	    lat = splitter[0];
	    lng = splitter[1];

	    myLatLng = new google.maps.LatLng(lat, lng);
	    map.setZoom(15);
	    map.setCenter(myLatLng);
	}

	, GetGeocodeError: function(error) {
	    var me = this;

	    switch (error) {
	        case 'ZERO_RESULTS':
	            alert('The Google GeoCoding server returned an error. This may be due to an incorrect or incomplete postcode.');
	            break;
	        case 'INVALID_REQUEST':
	            alert('The Google GeoCoding server returned an error. This may be due to an incorrect or incomplete postcode.');
	            break;
	        case 'OVER_QUERY_LIMIT':
	            alert('There is currently a problem with the Google GeoCoding server, please try again later.');
	            break;
	        default:
	            alert('There was a problem with GeoCoding');
	    }
	}

	, DisplaySearchResults: function(data) {
	    var me = this;

	    $('#map').css('height', '485px');
	    $('.noResults').hide();

	    var tbl = $('#stockistResults');
	    var tbody = tbl.find('tbody');
	    var content;
	    var results;
	    var row;

	    tbody.empty();

	    for (i in data) {
	        var stockists = data[i];

	        row = $('<tr></tr>');
	        var td = ($('<td valign="top"></td>'));
	        //console.log();
	        if (stockists.DryEye && stockists.IsStockist) {
	            var icon = $('<img src="/Resources/Global/Images/Maps/sdm' + (parseInt(i) + 1) + '.png" class="gotoStockist" rel="' + stockists.Lat + ',' + stockists.Lon + '" alt="Stockist and Dry Eye Specialist" title="Stockist and Dry Eye Specialist" />').click(function() {
	                me.HideDirections();
	                me.ReCalcMap($(this).attr('rel'));
	            });
	        } else if (stockists.DryEye) {
	            var icon = $('<img src="/Resources/Global/Images/Maps/dm' + (parseInt(i) + 1) + '.png" class="gotoStockist" rel="' + stockists.Lat + ',' + stockists.Lon + '" alt="Dry Eye Specialist" title="Dry Eye Specialist" />').click(function() {
	                me.HideDirections();
	                me.ReCalcMap($(this).attr('rel'));
	            });
	        } else {
	            var icon = $('<img src="/Resources/Global/Images/Maps/m' + (parseInt(i) + 1) + '.png" class="gotoStockist" rel="' + stockists.Lat + ',' + stockists.Lon + '" alt="Stockist" title="Stockist" />').click(function() {
	                me.HideDirections();
	                me.ReCalcMap($(this).attr('rel'));
	            });
	        }
	        td.append(icon);
	        row.append(td);
	        row.append($('<td valign="top"><b>' + stockists.Name + '</b></td>'));
	        tbody.append(row);

	        row = $('<tr></tr>');
	        row.append($('<td valign="top">&nbsp;</td>'));
	        row.append($('<td valign="top"><b>' + stockists.Distance + me.GetUOM() + '</b></td>'));
	        tbody.append(row);

	        row = $('<tr></tr>');
	        row.append($('<td valign="top">&nbsp;</td>'));
	        row.append($('<td valign="top">' + stockists.FullAddress.replace(/','/g, '<br/>') + '</td>'));
	        tbody.append(row);

	        row = $('<tr></tr>');
	        row.append($('<td valign="top">&nbsp;</td>'));
	        row.append($('<td valign="top" class="last">' + stockists.Telephone.replace('<br/>', '') + '</td>'));
	        tbody.append(row);

	        row = $('<tr></tr>');
	        row.append($('<td valign="top">&nbsp;</td>'));
	        //var td = ($('<td valign="top"></td>'));
	        //var dir = $('<a href="" class="getDir" rel="">Get directions</a></td>')
	        row.append($('<td valign="top" class="last"><a href="" class="getDir" rel="' + $('#myPostcode').val() + ',' + stockists.PostCode.replace('<br/>', '') + '">Get directions</a></td>'));
	        tbody.append(row);

	    }
	}

	, DisplayNoResults: function() {
	    var me = this;

	    me.ClearNumberMarkers();
	    $('#map').empty().removeAttr('style').css('height', '10px');

	    $('.noResults').show();

	    var tbl = $('#stockistResults');
	    var tbody = tbl.find('tbody');
	    var row;

	    tbody.empty();

	    /*row = $('<tr></tr>');
	    row.append($('<td valign="top"><div class="noResults"><b>There are currently no stockists within your search area. <br/><br/>Please widen your search radius by changing the distance drop down above.</b></div></td>'));
	    tbody.append(row);*/

	}

	, GetUOM: function() {
	    var me = this;

	    //var uom = $('#uom').val();
	    var uom = 'm';

	    if (uom == 'm') {
	        return ' miles';
	    } else {
	        return ' kilometres'
	    }
	}

}
