﻿/* jQuery Cafe Map puller-in-er by Mark Holland */

(function(jQuery) {

    jQuery.fn.cafeMap = function(options) {

        var opts = $.extend({}, $.fn.cafeMap.defaults, options);
        var coords = cleanCoords(opts.coords);

        if (coords !== '') {
            var latLong = getLatLong(coords);
            if (latLong !== null) {

                $(this).each(function(i, val) {

                    var targetDivId = getTargetDivId($(this), i);
                    var map = createMap(targetDivId);
                    plotStore(map, latLong);
                    map.setCenter(latLong);
                    map.setZoom(9);

                    $('a.branch-calendar').attr('href', 'http://maps.google.co.uk/maps?q=' + coords);

                    $(this).show();
                });
            }
        }

        return this;
    };

    jQuery.fn.cafeMap.defaults =
    {
        coords: ''
    };

    function cleanCoords(coords) {
        var htmlStripRegex = new RegExp('<(.|\n)*?>', 'ig');
        return coords.replace(htmlStripRegex, '').trim();
    }

    function getTargetDivId(container, i) {

        var targetDivId = container.find('.branch_map').attr('id');
        if (targetDivId === '') {
            targetDivId = 'branch_map' + i;
            container.find('.branch_map').attr('id', targetDivId);
        }
        return targetDivId;
    }

    function createMap(branch_map) {

        var britain = new google.maps.LatLng(54, -1);
        var map_opts = {
            center: britain,
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false
        };
        return new google.maps.Map(document.getElementById(branch_map), map_opts);
    }

    function getLatLong(coords) {

        coords = coords.split(',');
        if (coords.length < 2)
            return null;

        var latitude = parseFloat(coords[0].trim());
        if (isNaN(latitude))
            return null;

        var longitude = parseFloat(coords[1].trim());
        if (isNaN(longitude))
            return null;

        return new google.maps.LatLng(latitude, longitude);
    }

    function plotStore(map, latLong) {

        return new google.maps.Marker({
            map: map,
            position: latLong
        });
    }

    //
    // end of closure
    //
})(jQuery);
