$(document).unload(function() { GUnload(); })

var BASEURL             = "/";
var BASEURL_DETAIL_PAGE = "/msnDocDetails/index?docId=";
var BASEURL_MAPS_OVERLAY= "/maps/overlay";

var INITIAL_DISTANCE = 7;
var DEFAULT_DISTANCE = 15;

var map;
var geocoder;
var addresses;
var markerCount=0; 
var locationBounds;
var isPopup=false; 

function createGMap(elementId) {
    if(GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(elementId));
        locationBounds = new GLatLngBounds();
        map.setUIToDefault();
        geocoder = new GClientGeocoder(); 
        map.setCenter(new GLatLng(50.781200235659, 11.594030111), INITIAL_DISTANCE);
        addresses = getAddresses();



        addMapLocation(0);

        //updateViewport();
        if(isPopup) {
            createDocLegend();
        } else if(addresses.length>0) {
            createEnlargeButton(elementId);
        }
    }
}

function updateViewport() {
    if(addresses.length==1) {
        focusOn(0);
        //console.log("only one address");
    } else if(addresses.length>0){
        //console.info(locationBounds);
        //map.setZoom(map.getBoundsZoomLevel(locationBounds));
        map.setCenter(locationBounds.getCenter(), map.getBoundsZoomLevel(locationBounds));
    }
}

function createAddresses() {
    if(isPopup && top!=self) {
        return top.getAddresses();    
    }

    var addresses = new Array();
    var images = top.document.getElementsByName("marker");

    for (var n = 0; n != images.length; ++n) {
        var img = images[n];
        addresses.push(createDocAddr(n+1, img.getAttribute('alt'), img));
    }
    return addresses;
};

/**
 * Converts given data to an internal object-structure used to
 * put the marker onto the map.
 * Format: doc-name||address||categories with comma||ratingnumber||doc-id||lat||lon
 * @param index position of doctor within list
 * @param data string that contains doc-data separated by ||
 * @param marker path to marker-image for that doctor
 */
function createDocAddr(index, data, img) {
    img = checkImg(img);

    var a = data.split('||');
    var addr =	{
        index: index,           // position of this doctor within list
        name: a[0],             // doc-name
        addr: a[1],             // complete address
        type: a[2],             // categories
        rate: a[3],             // rating
        detailID: a[4] || 0,    // doc-id
        geoLat: a[5],
        geoLon: a[6],
        found: 0,
        img: img.src,
        marker: null, 
        point: 0,	// to be added by geocoder callback
        imgW: img.width,
        imgH: img.height
    };
    if (!addr.addr.match(/(?:germany|deutschand)/i)) addr.addr += ', Germany';

    return addr;
};

function checkImg(img)  {
    var res = img;
    var type = typeof img; 
    if(type != "object") {
        res = new Image();
        res.src=img;
    } 
    return res; 
}   

function createEnlargeButton(elementId) {
	var mapDiv = jQuery(document.getElementById(elementId));
	var mapWidth = mapDiv.width();
	var mapHeight = mapDiv.height();
        var imgL = mapWidth-118;
        var imgT = mapHeight-45;
        var img = '<img src="'+BASEURL+'images/buttons/but_groesser.png" style="position:absolute;z-index:10;left:'+imgL+'px;top:'+imgT+'px" />';
	var enlargeButton = '<a href="'+BASEURL_MAPS_OVERLAY+'?page=map&KeepThis=true&TB_iframe=true&width=886&height=570" class="thickbox">'+img+'</a>';
	mapDiv.append(jQuery(enlargeButton).setThickbox());
};






function addMapLocation(addressIndex) {
    if(map && geocoder) {
        geocoder.getLatLng(addresses[addressIndex].addr, function(point) {
            //console.log("RECEIVED LOCATION FOR: "+addressIndex+"   --> "+point); 
            addr = addresses[addressIndex];
            //console.log("Received: "+addressIndex+" with point: "+point);

            icon = new GIcon(G_DEFAULT_ICON);
            icon.iconSize = new GSize(addr.imgW, addr.imgH);
            
            //FIXME: Google-Bug? Setzen verschiebt den Marker um etwa einen KB nach NW...
            //icon.iconAnchor = new GSize(9,34);
            icon.image=addr.img;
            icon.shadow=null;

            addr.marker = new GMarker(point, {icon: icon});

            addr.point = point;
            
            locationBounds.extend(point);
            if(addresses.length==1) {
                map.setCenter(point, DEFAULT_DISTANCE);
                //map.setZoom(DEFAULT_DISTANCE); 
            } else {
                map.setCenter(locationBounds.getCenter(), map.getBoundsZoomLevel(locationBounds));
            }
            

            map.addOverlay(addr.marker);

            ++addressIndex
            if(addressIndex < addresses.length) {
                
                setTimeout('addMapLocation('+addressIndex+');',250);
            }
        } );
    }
}

function centerLocation(index) {
    focusOn(index);    
}

function createDocLegend() {
    var docLegend = document.getElementById("docLegend");
    var content = "";
    if (docLegend != null) {
        for (var n = 0; n<addresses.length; n++) {
            var addr = addresses[n];
            content += "<div>"
            content +=      "<div style='float:left; width: 22px;'>"
            content +=          "<img src='"+addr.img+"' style='cursor: pointer;' onclick='focusOn ("+n+")'/>";
            content +=      "</div>"
            content +=      "<div style='float:left; width: 215px;'>"
            content +=          "<h5>"+addr.name+"</h5>";
            content +=          "<small>"+addr.type+"</small>";
            content +=      "</div>"
            content += "</div>"
            content += "<div class='break'></div>";
            content += "<div class='sp1'></div>";
        }
        docLegend.innerHTML = content;
    }
};

function getAddresses() { 
    if(addresses==null) {
        addresses = createAddresses(); 
    }
    return addresses;
}

function toFront(addressNumber) {
    var addr = addresses[addressNumber];
    map.removeOverlay(addr.marker);
    map.addOverlay(addr.marker);
}


function focusOn(addressNumber) {
    //console.log("Focussing on: "+addressNumber+"   ---> ")
    toFront(addressNumber);
    map.panTo(addresses[addressNumber].point);
}