﻿   

        var loadCenter = [53.26267, -3.033105];
        var maxZoom = 11;
        var offsetZoom = 6;
        var currentZoom = 0;
        var slidePos = 0;

        var zoomForce;
        var map;
        var ll;
        var point;
        var opts;
        var marker;

        var newIcon;
        var normIcon;
        var newMarketOpts;
        var normMarketOpts;

        var currentMarker = null;
        var currentMarkerId = null;
        var existingMarkers = [];

        var xml;
        var directions;
        var searchLL;
        var locationsProximity = [];
        var locationsIds = [];

        var branchId;
        var schoolLL;

        var gotDirections = false;

        var geocoder = null;
        
    

        function initMap() {
            map = new google.maps.Map2(document.getElementById('map'));
            
            map.setCenter(new google.maps.LatLng(loadCenter[0], loadCenter[1]), offsetZoom);
            map.disableDoubleClickZoom();
            map.disableScrollWheelZoom();
            geocoder = new GClientGeocoder();
            directions = new GDirections(map, document.getElementById('mapDirectionsContainer'));
            
        }



        function createIcon(type) {
            var icon = new GIcon();
            var size = new GSize(38,35);
            var anchor = new GPoint(23,30);
            var window = new GPoint(15,0);
            var loc = 'images/';

            icon.image = loc + type + '_pin.png';
            icon.iconSize = size;
            icon.iconAnchor = anchor;
            icon.infoWindowAnchor = window;
            return icon;
        }

        function initMarkers() {
           
            // Creates a marker whose info window displays the letter corresponding
            // to the given index.
            //marker with ext info window with a red skin
            var redIcon1 = new GIcon(G_DEFAULT_ICON);
            redIcon1.iconAnchor = new GPoint(10, 32);
            redIcon1.infoWindowAnchor = new GPoint(7, 0);

            function createMarker(point, index, type) {
                markerOptions = createIcon(type);
                //markerOptions = redIcon1;
                var marker = new GMarker(point, markerOptions);
                existingMarkers.push(marker);

                GEvent.addListener(marker, "click", function() {
                    if (typeof MyOverlay !== 'undefined') {
                        if (currentMarker) {
                            closeOverlay();
                        }
                        if (!this.overlay) {
                            // just recording this for use in the closeOverlay function
                            this.overlay = new MyOverlay(this, generateInfoWindowContent(index));
                        }
                        currentMarker = this;
                        currentMarkerId = index;
                        map.panTo(new GLatLng(point.lat(), point.lng()));
                        map.addOverlay(this.overlay);
                        //this.hide();
                    } else {
                        marker.openInfoWindowHtml(generateInfoWindowContent(index));
                    }
                });
                return marker;
            }

            $('school', xml).each(function(i) {
                ll = $(this).find('ll').text().split(',');
                latlng = new GLatLng(ll[0], ll[1]);
                //var postcode = $(this).find('postcode').text()
                var type = $(this).find('type').text();
                map.addOverlay(createMarker(latlng, i, type));
                createListing(i, $(this).find('name').text(), type);
            });
        }

        function createListing(id, text, type) {
            $("#listing ul#" + type).append("<li><a href='#' onclick='showSchool(" + id + "); return false;'>" + text + "</a></li>"); 
        }
        
        function showSchool(id) {
            GEvent.trigger(existingMarkers[id], 'click');
        }
        // Customer Overlay code
        var MyOverlay = function(marker, html) {
            this.marker = marker;
            this.html = html;
        }
        MyOverlay.prototype = new GOverlay();
        MyOverlay.prototype.initialize = function(map) {
            var div = document.createElement("div");
            div.className = 'mywindow';
            div.innerHTML = this.html;
            // offsets based on popup div dimensions
            offsetX = 170; //193;
            offsetY = 191; //261;
            
            var p = map.fromLatLngToDivPixel(new GLatLng(this.marker.getPoint().y, this.marker.getPoint().x));

            div.style.top = (p.y - offsetY) + 'px';
            div.style.left = (p.x - offsetX) + 'px';
            div.style.position = 'absolute';

            div.onclick = closeOverlay;

            this._map = map;
            this._div = div;

            map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
        }
        MyOverlay.prototype.remove = function() {
            this._div.parentNode.removeChild(this._div);
        }
        MyOverlay.prototype.redraw = function() {
            //haven't had need for this yet
        }
        function closeOverlay() {
            if (currentMarker) {
                map.removeOverlay(currentMarker.overlay);
                currentMarker.show();
            }
        }




        function generateInfoWindowContent(i) {
            var content = $(xml).find('school').eq(i);
            var address = jQuery.trim(content.find('address').text());
            var name = jQuery.trim(content.find('name').text());
            
            var html;

            html = '<div class="infoWindow"><div class="infoWindowBg" onclick="closeOverlay();"></div><a href="#map" onclick="closeOverlay()" class="infoWindowClose"></a><div class="infoWindowAddress">' +
            '<strong id="infoWindowName">' + name +'</strong><br /><span id="infoWindowOfficeAddress"> ' + address + '</span> ' +
            '<span id="infoWindowOfficePostcode">' + content.find('postcode').text() + '</span><br /><a href="mailto:' + content.find('email').text() + '">' + content.find('email').text() + '</a><br /><a href="http://'+ content.find('web').text() +'" target="_blank">'+ content.find('web').text() + '</a><br /><a href="javascript:;" onclick="showPostcodeWindow();" class="infoWindowDirections">Click here for directions</a>' +
            '<div class="infoWindowPhone"><div class="infoWindowPhoneNumber">Tel: ' + content.find('telephone').text() + '<br />Fax: ' + content.find('fax').text() + '</div></div></div></div>';

            return html;

        }



        function initControls() {
            $('#slider').slider({ 'steps': maxZoom, 'change': sliderMoved, 'min': 0, 'max': maxZoom });

            $('#zoomOut').bind('click', function() {
                slidePos--;
                doZoom(this);
            });

            $('#zoomIn').bind('click', function() {
                slidePos++;
                doZoom(this);
            });

            $('#moveLeft').bind('click', function() {
                
                map.panDirection(+1, 0);

                this.blur();

            });

            $('#moveUp').bind('click', function() {
                map.panDirection(0, +1);

                this.blur();

            });

            $('#moveDown').bind('click', function() {
                map.panDirection(0, -1);

                this.blur();

            });

            $('#moveRight').bind('click', function() {
                map.panDirection(-1, 0);

                this.blur();

            });
            $('.search_nearest').bind('click', function() {
                var val = $('#search_postcode').val();
                if (val.length > 0) {
                    geocoder.getLatLng(val, ShowLocalSchools);
                }
            });
            $('#search_directions').bind('click', function() {
                GetDirections(); 
            });


        }

        function GetDirections() {

                var val = $('#locationSearch2').val();
                 gotDirections = false;
                if (val.length > 0) {
                    directions.clear();

                    if (searchLL) {
                        $(xml).find('office').eq(currentMarkerId).each(function() {
                            branchLL = $(this).find('ll').text();

                        });

                        $('#mapDirectionsContainer').html('');

                        directions.clear();

                        closeOverlay(true);

                        directions.load(searchLL[0] + ',' + searchLL[1] + ' to ' + branchLL);

                        $('#mapDirectionsContainer').slideDown('normal');

                        GEvent.addListener(directions, 'addoverlay', setSliderPos);

                        gotDirections = true;

                    } else if ($('#locationSearch2').val()) {
                        $(xml).find('school').eq(currentMarkerId).each(function() {
                        schoolLL = $(this).find('ll').text();
                            //doSearch($('#locationSearch2'), 'geocode');
                        });

                        // get postcode lat long
                        var postcode = $('#locationSearch2').val();
                        geocoder.getLatLng(postcode, function(point) {
                            if (!point) {
                                alert(postcode + " not found");
                            }
                            else {
                                //map.setCenter(point, 13);
                                $('#mapDirectionsContainer').html('');
                                directionsPanel = document.getElementById('mapDirectionsContainer');
                                directions = new GDirections(map, directionsPanel);
                                var searchCommand = 'from:' + point.y + ',' + point.x + ' to: ' + schoolLL;
                                directions.load(searchCommand);
                                $('#postcodeContainer').hide();
                                //alert(marker);
                                //map.addOverlay(marker);
                                //marker.openInfoWindowHtml(address);
                            }
                        });
                        //searchLL = [localSearch.results[0].lat, localSearch.results[0].lng];

                        directions.clear();
                        closeOverlay(true);
                        //$('#mapDirectionsContainer').html('');

                    } else {
                        alert('Please enter your postcode');

                    }

                    //closeOverlay(($(f).attr('id') == 'locationSearch2' ? true : null));
                    //geocodePostCode(val,($(f).attr('id') == 'locationSearch2' ? 'geocode' : null));
                } else {
                    alert('Please enter a valid UK postcode');
                }
        }

        function ShowLocalSchools(point) {

            
            var cal = new GLatLng(point.y, point.x);

            locationsProximity = [ ];

            $('school', xml).each(function(i) {
                var latlng = $(this).find('ll').text().split(',');
                var val = cal.distanceFrom(new GLatLng(latlng[0], latlng[1]));
                val = Math.round(val / 100) / 10;
                
                locationsProximity.push(val);
                locationsIds[val] = i;  
                      
            });

            locationsProximity.sort(function (a, b) {
            return a - b;

            });
            showSchool(locationsIds[locationsProximity[0]])
            //showWindow(locationsIds[locationsProximity[0]]);
        }
        
        function showPostcodeWindow() {
            if (currentMarkerId !== null) {
                //closeOverlay(true);

                $('#postcodeContainer').show();
                $('#locationSearch2').focus();

            } else {
                alert('Please select a branch');

            }

        }
        
        function initXML() {
            //debugger;
            $.get('locations.xml', null, parseXML, 'xml');

        }

        function parseXML(d, s) {
            //debugger;
            xml = d;
            //createIcon();
            initMarkers();
            //initLocations();
            //$.getScript('include/custominfowindow.js');

        }
        
        function showAddress(address) {
            geocoder.getLatLng(
                            address,
                            function(point) {
                                if (!point) {
                                    $("#msg").append('Postcode:' + address + 'not found<br />');
                                } else {
                                    $("#msg").append('Postcode:' + address + '|' + point.y + ',' + point.x + '<br />');
                                    //debugger;
                                    //                                    map.setCenter(point, 13);
                                    //                                    var marker = new GMarker(point);
                                    //                                    map.addOverlay(marker);
                                    //                                    marker.openInfoWindowHtml(address);
                                }
                            }
                          );
        }
        function doZoom(el) {
            var value = $('#slider').slider('option', 'value');
            $('#slider').slider('option', 'value', slidePos);
            ZoomMap(value);
            el.blur();
        }
        
        function sliderMoved(e, ui) {
            var value = $('#slider').slider('option', 'value');
            ZoomMap(value);
        }

        function ZoomMap(v) {
            currentZoom = v + offsetZoom;
            slidePos = v;

            if (!zoomForce) {
                map.setZoom(Math.round(currentZoom));
            } else {
                zoomForce = null;
            }
        }




        // Listing
        function initMenu() {
            $('#listing ul li ul').hide();
            $('#listing ul li ul:first').show();
            $('#listing ul li a').click(
            function() {
                var checkElement = $(this).next();
                if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                    return false;
                }
                if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                    $('#listing ul li ul:visible').slideUp('normal');
                    checkElement.slideDown('normal');
                return false;
                }
                }
            );
        }

    
