var map;
var geocoder;
var storeArray = new Array();

function initialize() {
    if (GBrowserIsCompatible()) {
        // Set search country to UK
        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode('uk');

        // Generate map
        map = new GMap2(document.getElementById('map_canvas'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(54.5, -2), 5);
    }
}

function searchLocations(address, option_gap, option_baby, option_kids,
    option_maternity, option_ps, option_body, option_outlet) {
    geocoder.getLatLng(address, function(latlng) {
        if (!latlng) {
            // Get sidebar element
            var sidebar = document.getElementById('sidebar');
            sidebar.innerHTML = "<p class='error'>Couldn't find address.</p>";
            return;
        } else {
            searchLocationsNear(latlng, address, option_gap, option_baby,
                option_kids, option_maternity, option_ps, option_body,
                option_outlet);
        }
    });
}

function searchLocationsNear(center, search_address, option_gap, option_baby,
    option_kids, option_maternity, option_ps, option_body, option_outlet) {
    //  Get all stores in a 20 mile radius from the search point
    var radius = 60;
    var searchUrl = '/stores/search.php' +
                    '?lat=' + center.lat() +
                    '&lng=' + center.lng() +
                    '&radius=' + radius +
                    '&option_gap=' + option_gap +
                    '&option_baby=' + option_baby +
                    '&option_kids=' + option_kids +
                    '&option_maternity=' + option_maternity +
                    '&option_ps=' + option_ps +
                    '&option_body=' + option_body +
                    '&option_outlet=' + option_outlet;

    // Call the search URL and get returned XML document
    GDownloadUrl(searchUrl, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('marker');

        map.clearOverlays();

        // Generate Sidebar HTML
        var sidebar = document.getElementById('sidebar');
        sidebar.innerHTML = '';

        // If no markers just show UK map and error message
        if (markers.length == 0) {
            sidebar.innerHTML = '<p class="error">No results found.</p>';
            map.setCenter(new GLatLng(54.5, -2), 5);
            return;
        }

        // Get bounds
        var bounds = new GLatLngBounds();

        // Loop through each location and attach events
        for (var i = 0; i < markers.length; i++) {

            // Grab all the info from xml
            var storeID = markers[i].getAttribute('store_id');
            var name = markers[i].getAttribute('name');
            var address = markers[i].getAttribute('address');
            var telno = markers[i].getAttribute('telno');

            var baby = markers[i].getAttribute('baby');
            var gap = markers[i].getAttribute('gap');
            var kids = markers[i].getAttribute('kids');
            var maternity = markers[i].getAttribute('maternity');
            var personal_shopper = markers[i].getAttribute('personal_shopper');

            var monday = markers[i].getAttribute('monday');
            var tuesday = markers[i].getAttribute('tuesday');
            var wednesday = markers[i].getAttribute('wednesday');
            var thursday = markers[i].getAttribute('thursday');
            var friday = markers[i].getAttribute('friday');
            var saturday = markers[i].getAttribute('saturday');
            var sunday = markers[i].getAttribute('sunday');

            var distance = parseFloat(markers[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                    parseFloat(markers[i].getAttribute('lng')));
            // Plot marker
            var marker = createMarker(storeID, point, name, address);
            map.addOverlay(marker);

            // Add sidebar entry
            var sidebarEntry = createSidebarEntry(storeID, marker, name,
                address, distance);
            sidebar.appendChild(sidebarEntry);

            // Build array of store data
            storeArray['store_' + storeID] = [storeID, name, address, telno,
                baby, gap, kids, maternity, personal_shopper,
                monday, tuesday, wednesday, thursday, friday, saturday,
                sunday];

            // Marker click
            GEvent.addDomListener(marker, 'click', function() {
                buildStoreInfo(this.id)
            });

            bounds.extend(point);
        }

        // Plot search marker
        var search_marker = new GMarker(center, initSearchIcon());
        map.addOverlay(search_marker)

        // Set map center
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    });
}

function buildStoreInfo(store_id) {
    // Get store info container to start building content
    var storeInfoElement = document.getElementById('storeContainer');

    // Remove intro copy
    $('#storeIntro').remove();

    // Grab variables from the store array
    var storeID = storeArray[store_id][0];
    var name = storeArray[store_id][1];
    var address = storeArray[store_id][2];
    var telno = storeArray[store_id][3];

    var baby = storeArray[store_id][4];
    var gap = storeArray[store_id][5];
    var kids = storeArray[store_id][6];
    var maternity = storeArray[store_id][7];
    var personal_shopper = storeArray[store_id][8];

    var monday = storeArray[store_id][9];
    var tuesday = storeArray[store_id][10];
    var wednesday = storeArray[store_id][11];
    var thursday = storeArray[store_id][12];
    var friday = storeArray[store_id][13];
    var saturday = storeArray[store_id][14];
    var sunday = storeArray[store_id][15];

    // Store Ranges
    var gap_ranges = [];
    if (gap != 0) {
        gap_ranges.push('<li>Gap</li>');
    }
    if (baby != 0) {
        gap_ranges.push('<li>babyGap</li>');
    }
    if (kids != 0) {
        gap_ranges.push('<li>GapKids</li>');
    }
    if (maternity != 0) {
        gap_ranges.push('<li>GapMaternity</li>');
    }

    // Build Store info HTML
    var storeHTML = "<div class='store_details'>" +
                        "<h1>" + name + "</h1>" +
                        "<address>" + address + "</address>" +
                        "<p class='telephone'><strong>Tel:</strong> <span>" + telno +"</span></p>" +
                        "<p><strong>Available ranges:</strong></p>" +
                        "<ul class='storeRanges'>" + gap_ranges.join('') + "</ul>";
                    "</div>";

    // Check if store offers personal shopper service
    if (personal_shopper != 0) {
        // Build stylist HTML
        var stylistHTML = "<div class='store_style'>" +
                              "<h2>Book A Personal Stylist</h2>" +
                              "<p>Our Personal Styling service is available at this store. Book your complimentary appointment online.</p>" +
                              "<a href='/personal-stylist/?pstore=" + storeID + "' class='button arrow'>Book Now</a>";
                          "</div>";
    } else {
        var stylistHTML = '';
    };

    // Check if store opening hours exist
    if (monday == null || tuesday == null || wednesday == null || thursday == null || friday == null || saturday == null || sunday == null ) {
        var hoursHTML = '';
    } else {
        // Build opening hours HTML
        var hoursHTML = "<div class='store-hours'>" +
                            "<h2>Opening Hours</h2>" +
                            "<ul>" +
                                "<li class='mon'><span>Monday</span> <em>" + monday + "</em></li>" +
                                "<li class='tue'><span>Tuesday</span> <em>" + tuesday + "</em></li>" +
                                "<li class='wed'><span>Wednesday</span> <em>" + wednesday + "</em></li>" +
                                "<li class='thu'><span>Thursday</span> <em>" + thursday + "</em></li>" +
                                "<li class='fri'><span>Friday</span> <em>" + friday + "</em></li>" +
                                "<li class='sat'><span>Saturday</span><em>" + saturday + "</em></li>" +
                                "<li class='sun'><span>Sunday</span> <em>" + sunday + "</em></li>" +
                            "</ul>" +
                        "</div>";
    };

    // Combine the HTML sections and insert into store info container
    storeInfoElement.innerHTML = storeHTML + stylistHTML + hoursHTML;

}

function initBaseIcon() {
    var bicon = new GIcon(G_DEFAULT_ICON);
    bicon.shadow = MEDIA_URL + "site_images/icons/map_marker_shadow.png";
    bicon.iconSize = new GSize(22, 41);
    bicon.shadowSize = new GSize(49, 41);
    bicon.iconAnchor = new GPoint(9, 34);
    bicon.infoWindowAnchor = new GPoint(15, 2);
    bicon.image = MEDIA_URL + "site_images/icons/map_marker.png";
    return bicon;
}
function initSearchIcon() {
    var bicon = new GIcon(G_DEFAULT_ICON);
    bicon.shadow = MEDIA_URL + "site_images/icons/map_marker_shadow.png";
    bicon.iconSize = new GSize(22, 41);
    bicon.shadowSize = new GSize(49, 41);
    bicon.iconAnchor = new GPoint(9, 34);
    bicon.infoWindowAnchor = new GPoint(15, 2);
    bicon.image = MEDIA_URL + "site_images/icons/map_marker_search.png";
    return bicon;
}

/* Not used atm
function initActiveIcon() {
    var bicon = new GIcon(G_DEFAULT_ICON);
    bicon.shadow = MEDIA_URL + "site_images/icons/map_marker_shadow.png";
    bicon.iconSize = new GSize(22, 41);
    bicon.shadowSize = new GSize(49, 41);
    bicon.iconAnchor = new GPoint(9, 34);
    bicon.infoWindowAnchor = new GPoint(15, 2);
    bicon.image = MEDIA_URL + "site_images/icons/map_marker_active.png";
    return bicon;
}
*/

function createMarker(store_id, point, name, address) {
    var marker = new GMarker(point, initBaseIcon());
    marker.id = 'store_' + store_id;

    GEvent.addListener(marker, 'click', function() {
        // Center map on point, pan to location and zoom in to zoom level 17
        map.setCenter(point);
        map.panTo(point);
        map.setZoom(17);
    });

    return marker;
}

function createSidebarEntry(store_id, marker, name, address, distance) {
    var li = document.createElement('li');
    var html = '<span><a href="#">' + name + '</a> - (' + distance.toFixed(1) + ' miles)</span>' +
               '<a href="#" class="button map">View</a>';
    li.innerHTML = html;
    li.setAttribute('id', 'store_' + store_id);

    GEvent.addDomListener(li, 'click', function() {
        GEvent.trigger(marker, 'click');
    });

    return li;
}
