// global variables
var map = null;
var progressBar = null;
var sidebar = null;
var markers = null;
var currentMarker = null;
var waitingForFirstClick = true;
var zoomListener = null;
var moveListener = null;
var searchActive = false;
var zoomActive = false;
var hobbyShopSiteCollection = {}; // associative array of hobbyShopSite objects
var hobbyShopSiteCollectionLength = 0;
var curvy = {};
var busyAddingMarkers = false; // reentrancy problems - should prevent get markers while adding...
var baseIcon = null;
var appRoot = null;

// initialize the map when jquery is 'ready'
$(document).ready(function() {
    initializeHobbyShopMap();
});

// register the unload function
$(window).unload(function() { GUnload(); });

function hobbyShopSite(id, xml)
// constructor for the hobbyShopSite object
{
    //showStatus('Adding site: ' + id);
    this.id = markers[currentMarker].getAttribute('id');
    this.number = markers[currentMarker].getAttribute('number');
    this.name = markers[currentMarker].getAttribute('name');
    this.email = markers[currentMarker].getAttribute('email');
    this.address0 = markers[currentMarker].getAttribute('address0');
    this.address1 = markers[currentMarker].getAttribute('address1');
    this.phone = markers[currentMarker].getAttribute('phone');
    this.fax = markers[currentMarker].getAttribute('fax');
    this.point = new GLatLng(parseFloat(markers[currentMarker].getAttribute('lat')),
	                             parseFloat(markers[currentMarker].getAttribute('lng')));
}

function toggleRefresh() {
    var form = document.getElementById('hobbyshopmapform');
    var autoRefresh = getRefreshState(form) == 1;
    form.refresh.disabled = autoRefresh;
    if (autoRefresh) refreshSites();
}

// returns 1 for automatic, 0 for manual 
function getRefreshState() {
    var form = document.getElementById('hobbyshopmapform');
    for (i = 0; i < form.autoRefresh.length; i++) {
        if (form.autoRefresh[i].checked == true)
            var zoom = form.autoRefresh[i].value;
    }
    return Number(zoom);
}

function showStatus(msg, replace) {
    var status = document.getElementById('status');
    if (replace === true) {
	    status.innerHTML = msg + '<br>';
    }
    else {
	    status.innerHTML = status.innerHTML + msg + '<br>';
    }
}

function getZoomLevel() {
    var form = document.getElementById('hobbyshopmapform');
    for (i = 0; i < form.zoom.length; i++) {
        if (form.zoom[i].checked == true)
            var zoom = form.zoom[i].value;
    }
    return Number(zoom);
}

function initializeHobbyShopMap() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        zoomListener = GEvent.addListener(map, "zoomend", onZoom);
        zoomListener = GEvent.addListener(map, "moveend", onMove);
        map.setCenter(new GLatLng(44, -72), 6);
        var mapControl = new GSmallZoomControl();
        map.addControl(mapControl);
        mapControl = new GMapTypeControl();
        map.addControl(mapControl);
        map.addControl(mapControl);
        progressBar = new ProgressbarControl(map, { width: 150 });
        sidebar = document.getElementById('sidebar');
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
    	appRoot = document.getElementById('appRoot').getAttribute('href');
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = appRoot + "images/markers/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
	}
	else {
		alert('Your browser settings are not compatible with Google maps!');
	}
    document.getElementById('location').focus();
    window.onresize = doWindowOnSize;
    doWindowOnSize();
}

function doWindowOnSize()
{
	//showStatus('onResize width:' + $(window).width(), true);
	if ($(window).width() < 800) {
	$('#leftcol')[0].style.width = '100%';
	$('#rightcol')[0].style.width = '100%';
	}
	else {
	$('#leftcol')[0].style.width = '49%';
	$('#rightcol')[0].style.width = '49%';
	}
    var newHeight = $('#mapcontainer')[0].clientHeight -30;
    // ugh - could not find a browser neutral way to get padding!!!
    //	 - parseInt($('#mapcontainer')[0].currentStyle.paddingTop) 
    //	 - parseInt($('#mapcontainer')[0].currentStyle.paddingBottom);
    $('#sidecontainer')[0].style.height = newHeight + 'px';
    $('#sidebar')[0].style.height = (newHeight - 20) + 'px';
    $('.corner').corner();
}
function mapDivClicked(e)
// ugh - gmap click event is currently broken in FireFox and Safari so we do it with page click event
{
    if (waitingForFirstClick) {
        e = e || window.event;
        var cursor = { x: 0, y: 0 };
        if (e.pageX || e.pageY) {
            cursor.x = e.pageX;
            cursor.y = e.pageY;
        }
        else {
            var de = document.documentElement;
            var b = document.body;
            cursor.x = e.clientX +
		            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
            cursor.y = e.clientY +
		            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
        }
        offset = cursorPageCoordinateToDiv(cursor, 'map_canvas');
        cursor.x -= offset.x;
        cursor.y -= offset.y;
        //alert('cursor position: ' + cursor.x + ', ' + cursor.y);
        latlng = map.fromContainerPixelToLatLng(new GPoint(cursor.x, cursor.y));
        document.getElementById('location').value = "";
        searchActive = true;
        waitingForFirstClick = false;
        map.setCenter(latlng, getZoomLevel());
    }
}

function cursorPageCoordinateToDiv(cursor, divid) {
    targetDiv = document.getElementById(divid);
    var offset = {};
    offset.x = bubbleX(targetDiv);
    offset.y = bubbleY(targetDiv);
    return offset;
}

function bubbleX(obj) {
    var x = obj.offsetLeft;
    while (obj = obj.offsetParent) x += obj.offsetLeft;
    return x;
}

function bubbleY(obj) {
    var x = obj.offsetTop;
    while (obj = obj.offsetParent) x += obj.offsetTop;
    return x;
}

function searchLocations() {
    // no more first click event
    var location = document.getElementById('location').value;
    if (location.search(/Type location here/i) >= 0)
    {
    	return false; // don't zoom until we have selected a location
    }
    if (waitingForFirstClick) {
        waitingForFirstClick = false;
    }
    if (location == '') {
        zoomActive = true;
        map.setZoom(getZoomLevel());
        return false;
    }
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(location, function(latlng) {
        if (!latlng) {
            alert('Location "' + location + '" not found');
        } else {
            hobbyShopSiteCollection = {}; // start over with new markers
            hobbyShopSiteCollectionLength = 0;
            map.clearOverlays();
            sidebar.innerHTML = '';
            document.getElementById('location').value = "";
            searchActive = true;
            // when the move event triggers, we will get the markers
            map.setCenter(latlng, getZoomLevel());
        }
    });
    return false;
}

function onZoom(oldZoom, newZoom) {
    //showStatus('onZoom - old: ' + oldZoom + ' new: ' + newZoom);
    //showStatus('searchActive: ' + searchActive + ' getRefreshState(): ' + getRefreshState() + ' clickListener: ' + clickListener);
    if (!searchActive) // search generates zoom then move - wait for the move
    {
        if ((zoomActive || (getRefreshState() == 1)) && !waitingForFirstClick) {
            //showStatus('zoom refreshing');
            zoomActive = false;
            refreshSites();
        }
    }
}

function onMove() {
    //showStatus('onMove');
    //showStatus('searchActive: ' + searchActive + ' getRefreshState(): ' + getRefreshState() + ' clickListener: ' + clickListener);
    if ((searchActive || (getRefreshState() == 1)) && !waitingForFirstClick) {
        //showStatus('move refreshing');
        searchActive = false;
        refreshSites();
    }
}

function refreshSites() {
    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    var searchUrl = appRoot +
				'pgms/getHobbyShops.php?lat1=' + ne.lat() + '&lng1=' + ne.lng() + '&lat2=' + sw.lat() + '&lng2=' + sw.lng();
    //window.location.href = searchUrl;
    if (waitingForFirstClick) {
        waitingForFirstClick = false;
    }
    if (busyAddingMarkers) return false;
    else busyAddingMarkers = true;
    GDownloadUrl(searchUrl, function(data) {
        var xml = GXml.parse(data);
        markers = xml.documentElement.getElementsByTagName('marker');
        if (markers.length == 0) {
        	busyAddingMarkers = false;
            return;
        }
        //showStatus('GDownloadUrl returned ' + markers.length + ' items');
        progressBar.start(markers.length);
        currentMarker = 0;
        setTimeout('addMarker()', 10);
    });
}

// called on a timer so the progress bar will have an opportunity to update
function addMarker() {
    progressBar.updateLoader(1);
    //showStatus('addMarker: currentMarker value is ' + currentMarker);
    var id = markers[currentMarker].getAttribute('id');  // database id - always unique
    if (!(id in hobbyShopSiteCollection)) {
        var newSite = new hobbyShopSite(id, markers[currentMarker]);
        hobbyShopSiteCollection[id] = newSite;
        hobbyShopSiteCollectionLength++;
        var marker = addTabbedMarker(newSite);
        addSidebarEntry(marker, newSite);
    }

    if (++currentMarker < markers.length) {
        setTimeout('addMarker()', 10);
    } else {
        progressBar.remove();
        busyAddingMarkers = false;
    }
}

function addTabbedMarker(newSite) {
	var markerNum = hobbyShopSiteCollectionLength;
	var markerColor = 'blue';
	var markerName;
	if (markerNum < 99) {
		markerName = 'marker' + markerNum + '.png';
	} else {
		markerName = 'blank.png';
	}
	var newIcon = new GIcon(baseIcon);
	newIcon.image = appRoot + '/images/markers/' + markerColor + '/' + markerName;
	var markerOptions = { icon:newIcon };
	var marker = new GMarker(newSite.point, markerOptions);
	var tab1 = new GInfoWindowTab('Hobby Shop',siteTabHtml(newSite));
	var tab2 = new GInfoWindowTab('Directions',directionsTabHtml(newSite));
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowTabsHtml([tab1, tab2], {maxWidth:250});
	});
    map.addOverlay(marker);
    return marker;
}

function siteTabHtml(newSite)
{
	var html = newSite.name + '<br /><br />'
			+ '<br />' + newSite.address0 + '<br />' + newSite.address1 + '<br />'
			+ 'email: <a href="mailto:' + newSite.email + '">' + newSite.email + '</a><br />'
			+ 'phone: ' + newSite.phone  + '<br />'
			+ 'fax: ' + newSite.fax + '<br />'
			;
	return html;
}

function directionsTabHtml(newSite)
{
	var dest;
	dest = newSite.address0 + ' ' + newSite.address1;
	var html = newSite.name + '<br />'
			+ '<br />'
			+ 'Driving directions (particularly for GPS coordinates) are for travel estimating purposes only, '
			+ 'be sure to contact the hobby shop for specific directions.<br /><br />'
			+ 'Driving directions to<br />'
			+ '<a href="http://maps.google.com/maps?saddr=&amp;daddr='
			+ dest + '" target="_blank">' + dest 
			+ '</a>';
	return html;
}

function addSidebarEntry(marker, newSite) {
	var hobbyshopdiv = getOrAddHobbyShop(newSite);
    hobbyshopdiv.style.cursor = 'pointer';
    hobbyshopdiv.style.marginBottom = '5px';
    GEvent.addDomListener(hobbyshopdiv, 'click', function() {
        GEvent.trigger(marker, 'click');
    });
    GEvent.addDomListener(hobbyshopdiv, 'mouseover', function() {
        hobbyshopdiv.style.backgroundColor = '#eee';
    });
    GEvent.addDomListener(hobbyshopdiv, 'mouseout', function() {
        hobbyshopdiv.style.backgroundColor = '#6b7e93';
    });
    return;
}

function getOrAddHobbyShop(newSite) {
	var divid = 'hobbyshop' + newSite.number;
	var div = document.getElementById(divid);
	if (div == null)
	{
	    var div = document.createElement('div');
	    div.setAttribute('id', divid);
	    div.setAttribute('class', 'hobbyshop');
	    var prefix = '';
	    if (hobbyShopSiteCollectionLength < 99) {
	    	prefix = '#' + hobbyShopSiteCollectionLength + ': ';
	    }
	    var html = '<b>' + prefix + ' ' + newSite.name + '</b>';
	    div.innerHTML = html;
	    addHobbyShopInAlphaOrder(div, newSite);
	}
	return div;
}

function addHobbyShopInAlphaOrder(div, newSite)
{
	// jquery fails in ie8 'compatibility mode' - let's try it the old fashioned way
	for (var node = sidebar.firstChild; node != null; node = node.nextSibling)
	{
		var classname;
		if (node.attributes) { classname = node.getAttribute('class'); }
		if (classname == 'hobbyshop')
		{
			var existing = node.innerHTML.toUpperCase();
			var colon = existing.indexOf(':');
			existing = existing.substring(colon + 2);
			var newitem = ('<b>' + newSite.name).toUpperCase();
			if ( existing > newSite.name)
			{
				sidebar.insertBefore(div, node);
				return;  //**** EARLY EXIT ****
			}
		}
	}
	sidebar.appendChild(div);
}