$(function(){
	$('div.gmapSmall a.magnifier').click(function(){
		$('img.gmapLoading').show();

		var mapWidth = Math.round($(window).width() * 0.75);
		var mapHeight = Math.round($(window).height() * 0.75);

		ajaxUrl = '/ajax/offers/?ajaxAction=gmap&mapWidth=' + mapWidth + '&mapHeight=' + mapHeight + '&' + googleMapFilter;
        if (typeof(languageCode) != 'undefined')
            ajaxUrl = '/' + languageCode + ajaxUrl;
		$.ajax({
	        type: 'GET',
	        timeout: 30000,
	        url: ajaxUrl,
	        async: true,
	        dataType: 'xml',
	        success: function(xmlResponse){
	        	xmlData = $(xmlResponse).find('data');
	        	if (xmlData.length > 0) {
	        		$.fancybox({
	        			'content': xmlData.text(),
	        			'width': mapWidth,
	        			'height': mapHeight,
	        			'titleShow': false,
	        			'showNavArrows': false,
	        			'onComplete': function(currentArray, currentIndex, currentOpts) {
	        				$('#map_canvas_popup_background').height(mapHeight).width(mapWidth);
	        				googleMapInit('map_canvas_popup', googleMapFilter);
	        			}
	        		});
	        	}
	        },
	        complete: function(jqXHR, textStatus) {
	        	$('img.gmapLoading').hide();
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
        		$('img.gmapLoading').hide();
	            if ((jqXHR.status != 200) && (typeof(textStatus) != 'undefined') && (textStatus != '')) {
	               alert(textStatus);
	            }
	        }
	    });
		return false;
	});
});

//listen for load event
$(window).load(function(){
	if (typeof(googleMapFilter) != 'undefined') {
		googleMapInit('map_canvas', googleMapFilter);
	}
});

function googleMapInit(mapId, googleMapFilter){
	if($('#' + mapId).length == 0) {
        return;
    }
	
	if ($.browser.msie && ($.browser.version < 7)) {
		$('#' + mapId + '_text span, div.gmapSmall a.magnifier').hide();
		$('#' + mapId + '_text .unsupportedBrowser').show();
		return;
	}

	var myZoom = 6;
	var maxZoom = 15;
	var minZoom = 6;
    var centerLat = 49.75;
    var centerLng = 15.50;

    var markerClustererOptions = {
    		'maxZoom': maxZoom,
    		'styles':
    			[{
	    			url: '/web/webmaster24/tools/js/gmaps-utility-v3/markerclusterer/images/conv30.png',
	    		    height: 27,
	    		    width: 30,
	    		    anchor: [5, 0],
	    		    textColor: '#ffffff',
	    		    textSize: 10
    			}, {
    				url: '/web/webmaster24/tools/js/gmaps-utility-v3/markerclusterer/images/conv40.png',
    		        height: 36,
    		        width: 40,
    		        anchor: [10, 0],
    		        textColor: '#ffffff',
    		        textSize: 11
    			}, {
    				url: '/web/webmaster24/tools/js/gmaps-utility-v3/markerclusterer/images/conv50.png',
    		        height: 46,
    		        width: 50,
    		        anchor: [14, 0],
					textColor: '#ffffff',
    		        textSize: 12
		        }]
    };

    var myLatlng = new google.maps.LatLng(centerLat, centerLng);
	var myOptions = {
		maxZoom: maxZoom,
		minZoom: minZoom,
		zoom: myZoom,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
	};
	var map;
	var infoWindow = false;

	function calculateZoomAndCenter(objectsLatitudes, objectsLongitudes) {
        var minLatitude = Math.min.apply(Math, objectsLatitudes);
        var maxLatitude = Math.max.apply(Math, objectsLatitudes);
        var minLongitude = Math.min.apply(Math, objectsLongitudes);
        var maxLongitude = Math.max.apply(Math, objectsLongitudes);

        var latDiff = maxLatitude - minLatitude;
        var lngDiff = maxLongitude - minLongitude;

        var lngLatDiff = Math.max(latDiff, lngDiff);

        centerLat = (minLatitude + maxLatitude) / 2;
        centerLng = (minLongitude + maxLongitude) / 2;

        myZoom = maxZoom;
        // TODO overwrite
        if (lngLatDiff > 0.075) {
            myZoom = 12;
        }
        if (lngLatDiff > 0.12) {
            myZoom = 11;
        }
        if (lngLatDiff > 0.15) {
            myZoom = 10;
        }
        if (lngLatDiff > 0.4) {
            myZoom = 9;
        }
        if (lngLatDiff > 0.8) {
            myZoom = 8;
        }
        if (lngLatDiff > 2) {
            myZoom = 7;
        }
        if (lngLatDiff > 4) {
            myZoom = 6;
        }
	}

	function openInfoWindow(marker) {
		if (infoWindow !== false) {
			infoWindow.close();
		}
        infoWindow = new google.maps.InfoWindow({
            position: marker.position,
            content: loadOfferContent(marker.id)
        });
        infoWindow.open(map);
    }

    function loadOfferContent(id) {
        var html = '';

        formVars = {};
        formVars['random'] = new Date().getTime();
        formVars['offer_id'] = id;
        ajaxUrl = '/ajax/offers/?ajaxAction=gmapsInfoWindow';
        if (typeof(languageCode) != 'undefined')
            ajaxUrl = '/' + languageCode + ajaxUrl;
    	$.ajax({
            type: 'POST',
            timeout: 30,
            url: ajaxUrl,
            data: formVars,
            async: false,
            dataType: 'xml',
            success: function(xmlResponse){
                if ($('response', xmlResponse).length > 0 && $('result', xmlResponse).length > 0 && $('data', xmlResponse).length > 0) {
                    html = $('data', xmlResponse).text();
                }
            },
            error: function(err){
                if ((err.status != 200) && (typeof(err.statusText) != 'undefined') && (err.statusText != '')) {
                   alert(err.statusText);
                }
            }
        });
        return html;
    }
	
	function loadMapMarkers(googleMapFilter) {
		$('#' + mapId + '_text span').hide();
		$('#' + mapId + '_text .loadingOffersText, img.gmapLoading').show();

		ajaxUrl = '/ajax/offers/?ajaxAction=gmapMarkers&' + googleMapFilter;
        if (typeof(languageCode) != 'undefined')
            ajaxUrl = '/' + languageCode + ajaxUrl;
		
		$.ajax({
	        type: 'GET',
	        timeout: 30000,
	        url: ajaxUrl,
	        async: true,
	        dataType: 'xml',
	        success: function(xmlResponse){
	        	xmlData = $(xmlResponse).find('data');
	        	if (xmlData.length > 0) {
	        		
	        		markersArr = $.parseJSON(xmlData.text());
	        		
	        		var markers = new Array();

	        		var googleMapsObjectsLatitudes = new Array();
	        		var googleMapsObjectsLongitudes = new Array();
	        		
	        	    for (id in markersArr) {
	        	        var object = markersArr[id];
	        	        
	        	        googleMapsObjectsLatitudes.push(object.latitude);
	        	        googleMapsObjectsLongitudes.push(object.longitude);
	        	        
	        	        var latLng = new google.maps.LatLng(object.latitude, object.longitude);
	        	        
	        	        markerObj = new google.maps.Marker({
	        	            id: id,
	        	            map: map,
	        	            clickable: true,
	        	            draggable: false,
	        	            position: latLng,
	        	            onclick: function() {
	        	            	openInfoWindow(this);
        	            	}
	        	        });

	        	        markers.push(markerObj);

	        	        google.maps.event.addListener(markerObj, 'click', markerObj.onclick);
	        	    }

	        	    var markerCluster = new MarkerClusterer(map, markers, markerClustererOptions);

	        	    google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
	        	    	if (map.getZoom() == maxZoom) {
	        	    		if (infoWindow !== false) {
	        	    			infoWindow.close();
	        	    		}
	        	    		var cmarkers = cluster.getMarkers();
	        	    		ids = new Array();
	        	    		for (var i = 0; i < cmarkers.length; ++i) {
	        	    			ids.push(cmarkers[i].id);
	        	    		}
	        	    		infoWindow = new google.maps.InfoWindow({
	        	                position: cluster.getCenter(),
	        	                content: loadOfferContent(ids)
	        	            });
	        	            infoWindow.open(map);
	        	    	}
	        	    });
	        	    
	        	    calculateZoomAndCenter(googleMapsObjectsLatitudes, googleMapsObjectsLongitudes);
	        	    
	        	    map.setZoom(myZoom);
	        	    map.panTo(new google.maps.LatLng(centerLat, centerLng));

	            	$('#' + mapId + '_background, #' + mapId + '_text, img.gmapLoading').hide();
	        	} else {
	        		$('#' + mapId + '_text .noOffersText').show();
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
        		$('img.gmapLoading').hide();
	        	if (jqXHR.status != 200) {
	        		$('#' + mapId + '_text .noOffersText').show();
	        	}
	            if ((jqXHR.status != 200) && (typeof(textStatus) != 'undefined') && (textStatus != '')) {
	               alert(textStatus);
	            }
	        }
	    });
		
	}

    map = new google.maps.Map(document.getElementById(mapId), myOptions);

    if (typeof(googleMapFilter) == 'undefined') {
		var googleMapFilter = '';
	}
    loadMapMarkers(googleMapFilter);
}
