var MapTools = {
    map: null,
    marker_def: new Array(),
    shops: null,

    initMap: function(id, shops) {
        this.shops = shops;

        for (var i=0; i < shops.length; i++) {
            this.marker_def[shops[i].id] = {
                image: 'image/icon/icon_'+shops[i].id.toLowerCase()+'.png',
                iconSize: new GSize(24, 25), 
                iconAnchor: new GPoint(12, 12)
            };
        }

        this.map = new GMap2(document.getElementById('map'));
        this.map.setCenter(new GLatLng(center.lat, center.lng), center.zoom, this.map.getMapTypes()[0]);

        this.map.addControl(new GLargeMapControl());
        
        var traffic = new ExtMapTypeControl({showTraffic: true, showTrafficKey: true, enableTraffic: false });
        this.map.addControl(traffic);
        
        this.map.enableScrollWheelZoom();
        this.map.clearOverlays();

        for (var i=0; i < shops.length; i++) {
            this.createMarker(i);
        }
        this.createList('list');
    },

    createMarker: function(i_id) {
        var s = this.shops[i_id];
        var point = new GLatLng(s.lat, s.lng);
        var icon = new GIcon();
        for (p in this.marker_def[s.id]) {
            icon[p]= this.marker_def[s.id][p];
        }

        icon.infoWindowAnchor = new GPoint(65, 2);
        icon.dragCrossImage = '';
        icon.maxHeight = 0;

        var marker = new GMarker(point, { icon: icon });
        this.map.addOverlay(marker);
        marker.value = s.name;

        GEvent.addListener(marker, 'click', function() {
                MapTools.showPopup(shops[i_id]);
            });

        this.shops[i_id].marker = marker;
        return marker;
    },

    showPopup: function(s) {
        this.map.setZoom(16);
        this.map.panTo(new GLatLng(s.lat + 0.0015, s.lng + 0.002));

        if (this.map.getExtInfoWindow() != null) this.map.closeExtInfoWindow(); 

        s.marker.openExtInfoWindow(this.map, 'popup', this.getHTML(s), { paddingX: 0, paddingY: 0, beakLeft: 34 });
    },

    getHTML: function(shop) {
        result = '<table id="popcontent"><tr>' +
            '<td class="photo"><div class="imgframe"><img src="'+shop.photo+'"/></div></td>' +
            '<td class="paddr">' + 
            shop.name + '<br/>';
        for (i=0; i<shop.address.length; i++) {
            result = result + shop.address[i] + '<br/>';
        }  
        result = result + shop.phone + '<br/>';
        for (i=0; i<shop.hours.length; i++) {
            result = result + shop.hours[i] + '<br/>';
        }  
        result = result + this.getDirections(shop) + 
            '</td></tr></table>';
        return result;
    },

    getDirections: function(shop) {
        result = '<a target="_blank" href="http://maps.google.com/maps?daddr=';
        for (i=0; i<shop.address.length; i++) {
            if (i > 0) {
                result = result + this.urlEncode(' ');
            }
            result = result + this.urlEncode(shop.address[i]);
        }  
        return result + '">Get Directions</a>';
    },

    getDirectionsElement: function(shop) {
        var a = document.createElement('a');
        a.setAttribute('target', '_blank');
        a.setAttribute('href', 'http://maps.google.com/maps?daddr=' + this.urlEncode(shop.address + ' ' + shop.address2));
        a.appendChild(document.createTextNode('Get Directions'));
	return a;
    },

    urlEncode: function(clearString) {
        var output = '';
        var x = 0;
        clearString = clearString.toString();
        var regex = /(^[a-zA-Z0-9_.]*)/;
        while (x < clearString.length) {
            var match = regex.exec(clearString.substr(x));
            if (match != null && match.length > 1 && match[1] != '') {
                output += match[1];
                x += match[1].length;
            } else {
                if (clearString[x] == ' ')
                    output += '%20';
                else {
                    var charCode = clearString.charCodeAt(x);
                    var hexVal = charCode.toString(16);
                    output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
                }
                x++;
            }
        }
        return output;
    },

    getShowPopup: function (s) {
	return (function(e) {
            MapTools.showPopup(s);
        });
    },

    createList: function (id) {
        var t = document.createElement('table');
        document.getElementById(id).appendChild(t);
        var tb = document.createElement('tbody');
        t.appendChild(tb);
        for (var i=0; i < this.shops.length; i++) {
            var row = document.createElement('tr');
            tb.appendChild(row);
            row['onclick'] = this.getShowPopup(this.shops[i]);
            if (i % 2 == 0) {
                row.className = 'even';
            };
            var letter = document.createElement('td');
            row.appendChild(letter);
            letter.className = 'letter';
            letter.appendChild(document.createElement('br'));
            var l = document.createElement('h1');
            l.appendChild(document.createTextNode(this.shops[i].id));
            letter.appendChild(l);
            var info = document.createElement('td');
            row.appendChild(info);
            info.className = 'addr';
            var n = document.createElement('h2');
            n.appendChild(document.createTextNode(this.shops[i].name));
            info.appendChild(n);
            for (j=0; j<this.shops[i].address.length; j++) {
                info.appendChild(document.createTextNode(this.shops[i].address[j]));
                info.appendChild(document.createElement('br'));
            }
            info.appendChild(document.createTextNode(this.shops[i].phone));
            info.appendChild(document.createElement('br'));
            for (j=0; j<this.shops[i].hours.length; j++) {
                info.appendChild(document.createTextNode(this.shops[i].hours[j]));
                info.appendChild(document.createElement('br'));
            }
            info.appendChild(this.getDirectionsElement(shops[i]));
        }
    }

};

