﻿var LocationsXML;
var Locations;
var CurrentLocation;
var LocationHTML = '';

var directions = null;
var LocationsArray = new Array();
var map;

var searchLL;



function Office(officename, address, postcode, telephone, fax, email, est, title, firstname, lastname, counter, openingtimes, officeinfo, openingdate, ll, location, url, fullDetails, index) {
    this.officename = officename;
    this.address = address;
    this.postcode = postcode;
    this.telephone = telephone;
    this.fax = fax;
    this.email = email;
    this.est = est;
    this.title = title;
    this.firstname = firstname;
    this.lastname = lastname;
    this.counter = counter;
    this.openingtimes = openingtimes;
    this.officeinfo = officeinfo;
    this.ll = ll;
    this.location = location;
    this.index = index;
    this.lat = ll.split(',')[0];
    this.lng = ll.split(',')[1];
    this.openingdate = openingdate;
    this.url = url;
    this.fullDetails = fullDetails;
    //debugger;
    if (this.openingdate != '')
        this.newoffice = true;
    else
        this.newoffice = false;


    this.link = CreateLink(this);
    this.marker = CreateMarker(this);
    this.infowindowcontent = CreateInfoWindowContent(this);
}



        function CreateInfoWindowContent(Office) {
            var html;
            //debugger;
            if (Office.fullDetails == true) {

                html = '<div class="infoWindow">' +
                '<div class="infoWindowBg" onclick="Coutts.MarkClose();"></div><a href="#map" onclick="Coutts.MarkClose()" class="infoWindowClose"></a>' +
                '<div id="infoWindowOfficeMain_' + Office.index + '" class="infoWindowAddress">' +
		        '<strong id="infoWindowOfficeName">' + Office.officename + '</strong><br /><span id="infoWindowOfficeAddress"> ' + Office.address + '</span>, ' +
		        '<span id="infoWindowOfficePostcode">' + Office.postcode + '</span><br /><div class="infoWindowPhone"><div class="infoWindowPhoneNumber">Telephone: ' + Office.telephone + '</div></div><br /><a href="javascript:;" onclick="showPostcodeWindow(' + Office.index + ', true);" class="infoWindowDirections">Get Directions</a>' +
		        '<a href="' + Office.url + '" onclick="return true;" class="infoWindowFI">Further information</a>' +
		        '</div>' +
		        '<div id="infoWindowOfficeDirections_' + Office.index + '" class="infoWindowOfficePostcode" style="display:none;"> ' +
		        '' +
		        '<label class="searchinput"> Postcode: ' +
                '<input name="search" id="locationSearch_' + Office.index + '" class="search-box locationSearch" type="text"  onclick="this.focus(); return false;"  /> ' +
                '</lable><span class="searchsubmit" style="padding-left: 5px;"> ' +
                '<input name="go" class="go-button locationSearchGo" src="/images/c-frame/postcode-search.gif" type="image" onclick="GetDirections(' + Office.index + '); return false;" /> ' +
                '</span> ' +
                '<a href="javascript:;" onclick="showPostcodeWindow(' + Office.index + ', false);" class="infoWindowDirections">Cancel</a>' +
		        '</div>' +
		        '</div>';
            }
            else {
                html = '<div class="infoWindow">' +
                '<div class="infoWindowBg" onclick="Coutts.MarkClose();"></div><a href="#map" onclick="Coutts.MarkClose()" class="infoWindowClose"></a>' +
                '<div id="infoWindowOfficeMain_' + Office.index + '" class="infoWindowAddress">' +
		        '<strong id="infoWindowOfficeName">' + Office.officename + '</strong><br /><span id="infoWindowOfficeAddress"> ' + Office.address + '</span>, ' +
		        '<span id="infoWindowOfficePostcode">' + Office.postcode + '</span>' +
		        '<div class="infoWindowPhone"><div class="infoWindowPhoneNumber">Telephone: ' + Office.telephone + '</div></div><br /><a href="javascript:;" onclick="showPostcodeWindow(' + Office.index + ', true);" class="infoWindowDirections">Get Directions</a></div>' +
		        '<div id="infoWindowOfficeDirections_' + Office.index + '" class="infoWindowOfficePostcode" style="display:none;"> ' +
		        '' +
		        '<label class="searchinput"> Postcode: ' +
                '<input name="search" id="locationSearch_' + Office.index + '" class="search-box locationSearch" type="text"  onclick="this.focus(); return false;"  /> ' +
                '</lable><span class="searchsubmit" style="padding-left: 5px;"> ' +
                '<input name="go" class="go-button locationSearchGo" src="/images/c-frame/postcode-search.gif" type="image" onclick="GetDirections(' + Office.index + '); return false;" /> ' +
                '</span> ' +
                '<a href="javascript:;" onclick="showPostcodeWindow(' + Office.index + ', false);" class="infoWindowDirections">Cancel</a>' +
		        '</div>' +
		        '</div>';
            }
            return html;
        }

function showPostcodeWindow(Index, show) {
    CurrentLocation = Index;
    if (show) {
        if (Coutts.CurrentMarker != null) {
            $('#infoWindowOfficeMain_' + Index).hide();
            $('#infoWindowOfficeDirections_' + Index).show();
        } else {
            alert('Please select a branch');
        }
    }
    else {
        $('#infoWindowOfficeMain_' + Index).show();
        $('#infoWindowOfficeDirections_' + Index).hide();
    }

}
function SearchNearest() {
    var val = sanitizeInput($('#mapSearchValue').val());
    //debugger;
    if (val.length > 0) {
        directions.clear();
	// SC Tracking
	//debugger;
	s.prop11=val.toUpperCase();
	//debugger;
       
        GeocodePostCode(val, false);
    } else {
        alert('Please enter a valid UK postcode');
    }
}
function GetDirections(i) {
    var val = $('#locationSearch_' + i).val();
    //debugger;
    if (val.length > 0) {
        directions.clear();
        GeocodePostCode(val, true);
    } else {
        alert('Please enter a valid UK postcode');
    }
}
function GeocodePostCode(val, directions) {
    var localSearch = new GlocalSearch();
    //debugger;
    localSearch.setCenterPoint("uk");
    if (val.toLowerCase() != "monaco")
        val = val + " uk";
    var find = (arguments[1] == 'geocode' ? true : false);

    localSearch.setSearchCompleteCallback(null, function() {
        if (localSearch.results[0]) {
            searchLL = [localSearch.results[0].lat, localSearch.results[0].lng];
            if (directions)
                getDirections();
            else
                getNearest();
        } else {
            alert('Postcode not found');
        }
    });

    localSearch.execute(val);
}
function getNearest() {
    var cal = new GLatLng(searchLL[0], searchLL[1]);
	
    locationsProximity = [];
    var locationsIds = [];
    for (var i = 0; i < LocationsArray.length; i++) {
        var Office = LocationsArray[i];
        var val = cal.distanceFrom(new GLatLng(Office.lat, Office.lng));
        val = Math.round(val / 100) / 10;
        locationsProximity.push(val);
        locationsIds[val] = i;
    }
    locationsProximity.sort(function(a, b) {
        return a - b;
    });
    
   


    Coutts.HightlightOffice(locationsIds[locationsProximity[0]]);
   
    // SC Tracking
	
    s.prop12 = LocationsArray[locationsIds[locationsProximity[0]]].officename.toUpperCase();
    //alert(s.prop12);

    //scSetUpPageVars();
    scSetUpPageVars("event10");
}
function getDirections() {
    //debugger;
    if (searchLL) {
        $('#mapDirectionsContainer').html('');
        directions.clear();
        var SearchValues = searchLL[0] + ',' + searchLL[1] + ' to ' + Coutts.CurrentMarker.getLatLng();
        directions.load(SearchValues);
        $('#mapDirectionsContainer').slideDown('normal');
        Coutts.MarkClose();
    }
}

function CreateLink(Office) {
    var Link = '<a href="#" onclick="javascript:Coutts.HightlightOffice(' + Office.index + '); return false;">' + Office.officename + '</a>';
    return Link;
}
function CreateMarker(Office) {
    var point = new GLatLng(Office.lat, Office.lng);
    var opts = CreateIcon(Office.newoffice, Office.index);
    opts.title = Office.officename + (Office.newoffice ? ' (New office)' : '');  //'marker' + Office.index; //Office.officename + (Office.newoffice ? ' (New office)' : '');
    var marker = new GMarker(point, opts);
    return marker;
}
function CreateIcon(newOffice, index) {
    var size = new GSize(31, 33);
    var anchor = new GPoint(15, 33);
    var window = new GPoint(15, 0);
    var loc = '/images/locations/';
    //var loc = '';

    newIcon = new GIcon();
    normIcon = new GIcon();

    newIcon.image = loc + 'newpoint.png?ID=' + index;
    newIcon.iconSize = size;
    newIcon.iconAnchor = anchor;
    newIcon.infoWindowAnchor = window;

    normIcon.image = loc + 'normpoint.png?ID=' + index;
    normIcon.iconSize = size;
    normIcon.iconAnchor = anchor;
    normIcon.infoWindowAnchor = window;

    newMarketOpts = { 'icon': newIcon };
    normMarketOpts = { 'icon': normIcon };
    if (newOffice)
        return newMarketOpts;
    else
        return normMarketOpts;

}

var Coutts = {
    CurrentMarker: null,
    FullDetails: true,
    SelectedOffice: '',
    SelectedOfficeId: null,
    Init: function(details, selectedOffice) {
        //debugger;
        if (details != undefined)
            Coutts.FullDetails = details;
        if (selectedOffice != undefined)
            Coutts.SelectedOffice = selectedOffice;
	$.get("/include/locations.xml", Coutts.parseXML, 'xml');
        //$.get('http://coutts-redesign.coloni.net/locations.txt', null, Coutts.parseXML, 'xml');
    },
    parseXML: function(d, s) {
        //debugger;
	//alert(d);
        Coutts.InitOffice(d);
        if (Coutts.FullDetails == true) {
            Coutts.ListLocations(d);
        }
        Coutts.MarkLocations();

    },
    InitOffice: function(LocationsXML) {
	//alert(LocationsXML);
        $(LocationsXML).find("office").each(function(i) {		
            LocationsArray[LocationsArray.length++] =
                    new Office(
                        $(this).find('officename').text(),
                        $(this).find('address').text(),
                        $(this).find('postcode').text(),
                        $(this).find('telephone').text(),
                        $(this).find('fax').text(),
                        $(this).find('email').text(),
                        $(this).find('est').text(),
                        $(this).find('title').text(),
                        $(this).find('firstname').text(),
                        $(this).find('lastname').text(),
                        $(this).find('counter').text(),
                        $(this).find('openingtimes').text(),
                        $(this).find('officeinfo').text(),
                        $(this).find('openingdate').text(),
                        $(this).find('ll').text(),
                        $(this).find('location').text(),
                        $(this).find('url').text(),
                        Coutts.FullDetails,
                        ((LocationsArray.length) - 1)
                    );
        });
    },
    GetOfficeIndex: function(officename) {
        for (var i = 0; i < LocationsArray.length; i++) {
            if (LocationsArray[i].officename == officename)
                return i;
        }
    },
    ListLocations: function(LocationsXML) {
        $(LocationsXML).find("locations").each(function() {
            var Class = $(this).attr('Class');
            LocationHTML += '<li>' + $(this).attr('Name') + '<ul class="' + Class + '">';
            $(this).find("office").each(function() {
                //debugger;
                var OfficeName = $(this).find('officename').text();
                var OfficeIndex = Coutts.GetOfficeIndex(OfficeName);
                var Office = LocationsArray[OfficeIndex];
                LocationHTML += '<li>' + Office.link + '</li>';
            });
            LocationHTML += '</ul></li>';
        });
        $('#list').append(LocationHTML);
    },
    MarkerShowLocation: function() {
        //debugger;
        if (Coutts.CurrentMarker !== null) { Coutts.MarkClose(); }
        var m = this;
        var id = null;

        //id = m.getTitle();
        //id = id.replace('marker', '');

        var img = m.getIcon();
        var imagesrc = img.image;
        var idvalues = imagesrc.split("ID=");
        id = idvalues[1];
        var html = LocationsArray[id].infowindowcontent;
        this.overlay = new customWindow(this, html);
        if (Coutts.FullDetails == true){
	map.panTo(new GLatLng(this.getPoint().lat(), this.getPoint().lng()));
	}
	else
	{
		map.panTo(new GLatLng(this.getPoint().lat()+0.0005, this.getPoint().lng()+0.0007));
	}
        map.addOverlay(this.overlay);
        Coutts.CurrentMarker = this;
    },
    MarkClose: function() {
        //debugger;
        if (Coutts.CurrentMarker) {
            map.removeOverlay(Coutts.CurrentMarker.overlay);
            Coutts.CurrentMarker.show();
            if (!arguments[0]) {
                $('#tabs div').html('Please select an office to see more information about it.');
            }
            Coutts.CurrentMarker = null;
        }
        $('#postcodeContainer').hide();
    },
    MarkLocations: function(LocationsXML) {
        for (var i = 0; i < LocationsArray.length; i++) {
            if (Coutts.CurrentMarker !== null) { Coutts.MarkClose(); }
            if (Coutts.FullDetails == true) {
                GEvent.addListener(LocationsArray[i].marker, 'click', Coutts.MarkerShowLocation);
                map.addOverlay(LocationsArray[i].marker);
            }
            else if (LocationsArray[i].officename == Coutts.SelectedOffice) {
                GEvent.addListener(LocationsArray[i].marker, 'click', Coutts.MarkerShowLocation);
                map.addOverlay(LocationsArray[i].marker);
                Coutts.SelectedOfficeId = i;
                setTimeout('Coutts.HightlightSelectedOffice();', 500);
		break;
            }
        }
    },
    HightlightOffice: function(i) {
        //debugger;
        GEvent.trigger(LocationsArray[i].marker, 'click');
    }
    ,HightlightSelectedOffice: function() {
        //debugger;
    GEvent.trigger(LocationsArray[Coutts.SelectedOfficeId].marker, 'click');
    }
};
    
   

