var map, cluster, markers, loaded_locations = {};
var KEY_ENTER = 13;
var Cache = {
    CACHE_MAX_SIZE: 50,
    contents: {},
    set: function(key, value, overwrite) {
        overwrite = overwrite || false;
        if(!overwrite && Cache.contains(key)) {
            throw "Cannot overwrite value for " + key;
        }
        if(Cache.contents.length==Cache.CACHE_MAX_SIZE) {
            throw "Cache overflow";
        }
        this.contents[key] = value;
    },
    contains: function(key) {
        return typeof Cache.contents[key] != "undefined";
    },
    get: function(key) {
        if(!Cache.contains(key)) {
            throw "Unknow Cache key " + key;
        }
        return Cache.contents[key];
    },
    update: function(key, value) {
        if(!Cache.contains(key)) {
            throw "Cannot update " + key + ": key doesnt exists.";
        }
        Cache.set(key, value, 1);
    }
}
var maps = []
var clusters = [];

$(function () {
    if (!GBrowserIsCompatible()) {
    	return;
    }
    targets = [];
    if (document.getElementById("map")) {
    	targets.push(document.getElementById("map"));
    }
    if (document.getElementById("map-nocontrols")) {
    	targets.push(document.getElementById("map-nocontrols"));
    }
    if (targets.length == 0) {
    	return;
    }
    $(targets).each(function (ind) {
    	if ($(this).is('div')) {
    		if (window.parent.location.href != window.location.href) {
    			var map = new GMap2(this, {size: new GSize(584, 450)});
    		} else {
    			var map = new GMap2(this, {size: new GSize(700, 560)});
    		}
			var settings = {};
			if (typeof ZOOM_IMAGE!="undefined") {
				
				var icon = new GIcon();
				icon.image = ZOOM_IMAGE;
				icon.iconSize = new GSize(ZOOM_IMAGE_WIDTH, ZOOM_IMAGE_HEIGHT);
				
				icon.iconAnchor=new GPoint(9, 31);
				icon.infoWindowAnchor = new GPoint(9, 31);
				if (!NO_SHADOW) {
					icon.shadow = ZOOM_IMAGE_SHADOW;
					icon.shadowSize = new GSize(ZOOM_IMAGE_SHADOW_WIDTH, ZOOM_IMAGE_SHADOW_HEIGHT);
				}
				settings.clusterMarkerIcon = icon;
			}
			//clusters.push(new ClusterMarker(map, settings));
			if (this.id != 'map-nocontrols') {
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				map.setCenter(new GLatLng(DEF_LAT, DEF_LNG), DEF_ZOOM);
			} else {
				map.setCenter(new GLatLng(DEF_LAT, DEF_LNG), 9);
			}
			map.enableScrollWheelZoom();
			maps.push(map);
			
			$('#checkboxes input[type=checkbox]').click(reload_markers);
			reload_markers();
		}
    });
});

all_markers = [];
function create_location(location, open_onload) {
	if (typeof set_center == 'undefined') {
		set_center = false;
	}
	$(maps).each(function () {
		var latlng = new GLatLng(location.lat, location.lng);
		var marker = new GMarker(latlng);
		//, {
		//	icon: new GIcon(G_DEFAULT_ICON, "/uploads/mt_sections/icon/icons/" + location.map_icon[1])
		//}\
		var tooltip = new Tooltip(marker, location.name, 4);
		marker.tooltip = tooltip;
		this.addOverlay(tooltip);
		GEvent.addListener(marker,'mouseover',function(){ marker.tooltip.show(); });
		GEvent.addListener(marker,'mouseout',function(){ marker.tooltip.hide(); });
		GEvent.addListener(marker,'click',function(){ marker.tooltip.hide(); });
		GEvent.addListener(this,'zoomend',function(){ marker.tooltip.hide(); });
		
		var loading_html = "<div class='tab-content'><div style='width: 208px; display: block; text-align: center; margin: 15px auto;'>Loading ... please wait<br /><img src='/css/images/loading.gif' alt='' /><br /></div></div>";
		var tabs = [];
		tabs.push(new GInfoWindowTab("Main", loading_html));
		tabs.push(new GInfoWindowTab("Information", loading_html));
		tabs.push(new GInfoWindowTab("Contact", loading_html));
		
		if (this.o.id != 'map-nocontrols') {
			GEvent.addListener(marker, "click", function() {
				if (typeof loaded_locations[location.id] != "undefined") {
					marker.openInfoWindowTabs(loaded_locations[location.id], {maxWidth: '300'});
					return;
				}
				marker.openInfoWindowTabs(tabs);
				
				$.get('/get-location', {id: location.id}, function (response) {
					loaded_locations[response.id] = create_location_tabs(response);
					marker.openInfoWindowTabs(loaded_locations[response.id], {maxWidth: '300'});
				}, 'json')
			});
		}
	
		this.addOverlay(marker);
		all_markers.push(marker);
		return marker;
	});
}

function inline_iframe_thickbox(href) {
	tb_show("", href, "");
}

function create_location_tabs(location) {
	var tabs = [];
		
	var main_content_tab = "<div class='tab-content' style='width: 300px;'><strong>" + location.name + "</strong><br />";
	if (location.image360) {
		main_content_tab += "<img src='/uploads/mt_locations/image360/360/" + location.image360 + "' width='" + location.img_width + "' height='" + location.img_height + "' />";
	}
	var orig_loc = location.link360;
	if (location.link360.indexOf('?')==-1) {
		location.link360 += '?';
	} else {
		location.link360 += '&';
	}
	//location.link360 += 'TB_iframe=true&width=771&height=540';
	
	/*
	main_content_tab += "<div class='left location-icons'>";
	for (var i=0; i < location.icons.length; i++) {
		var ico = location.icons[i];
		var img = new Image();
		img.src = ico.src;
		var iwidth = img.width;
		var iheight = img.height;
		main_content_tab += "<img src='" + ico.src + "' alt='" + ico.title + "' width='" + iwidth + "' height='" + iheight + "' />";
	};
	*/
	
	main_content_tab += '</div>';
	if (orig_loc!='http://') {
		//main_content_tab += "<a href='" + location.link360 + "?TB_inline=true&width=800&height=550&inlineId=inline-hook&amp;strip_tb_titles=true' class='right thickbox-hook2'>View 360&deg; Panoramic</a>";
		main_content_tab += "<a href='" + location.link360 + "TB_inline=true&width=800&height=550&inlineId=inline-hook' class='right' onclick='hook_open_thickbox($(this).attr(\"href\")); return false;'>View 360&deg; Panoramic</a>";
	}
	
	tabs.push(new GInfoWindowTab("Main", main_content_tab));
	
	var information_tab = '<div class="tab-content tab-informaion">' + location.information + '</div>';
	
	tabs.push(new GInfoWindowTab("Information", information_tab));
	
	var contact_tab = "<div class='tab-content'>" + 
		"<table class='contact-tab-table'>" +
		"<tr><th>Address </th><td>" + location.address + "</td></tr>";
	if (location.phone_number) {
		contact_tab += "<tr><th>Telephone</th><td>" + location.phone_number + "</td></tr>";
	}
	if (location.fax_number) {
		contact_tab += "<tr><th>Fax Number </th><td>" + location.fax_number + "</td></tr>";
	}
	if (location.mail) {
		contact_tab += "<tr><th>Email</th><td><a href='mailto:" + location.mail + "'>" + location.mail + "</a></td></tr>";
	}
	if (location.url) {
		contact_tab += "<tr><th>Website</th><td><a href='/count-hit?id=" + location.id + "' target='_blank'>" + location.url + "</a></td></tr>";
	}
	contact_tab += "</table></div>";
	
	tabs.push(new GInfoWindowTab("Contact", contact_tab));
	
	return tabs;
}
function reload_markers_v2(ids, location_ids_provided) {
	if (typeof location_ids_provided == 'undefined') {
		location_ids_provided = 0;
	} else {
		location_ids_provided = 1;
	}
    //$('#checkboxes input:checked').each(function () { ids.push(this.value); });
    //if (ids.length == 0) {
    //	return;
    //}
    $.get('/get-locations', {ids: ids.join(','), add_junk: (typeof MANY == 'undefined' ? 0 : 1), loc_ids_provided: location_ids_provided}, function (locations, status) {
    	$(maps).each(function () {
    		this.clearOverlays();
		});
    	markers = [];
    	$(clusters).each(function () {
    		this.removeMarkers();
		});
    	Sidebar.clean_locations();

        for (var i=0; i < locations.length; i++) {
	    	markers.push(create_location(locations[i]));
	    	Sidebar.add_location(locations[i], i);
	    }
	    $(clusters).each(function () {
	    	this.addMarkers(markers);
	    	this.refresh();
    	});
	    
	    setTimeout(function () {
	        tb_init('.thickbox');
	    }, 1000);
	    
    }, 'json');
}
function reload_markers() {
	ids = [];
    $('#checkboxes input:checked').each(function () { ids.push(this.value); });
    //if (ids.length == 0) {
    //	return;
    //}
    $.get('/get-locations', {ids: ids.join(','), add_junk: (typeof MANY == 'undefined' ? 0 : 1)}, function (locations, status) {
    	// map.clearOverlays();
    	markers = [];
    	$(clusters).each(function () {
    		this.removeMarkers();
    	});
    	
    	Sidebar.clean_locations();

        for (var i=0; i < locations.length; i++) {
	    	markers.push(create_location(locations[i]));
	    	Sidebar.add_location(locations[i], i);
	    }
	    $(clusters).each(function () {
	    	this.addMarkers(markers);
	    	this.refresh();
    	});
	    
	    setTimeout(function () {
	        tb_init('.thickbox');
	    }, 1000);
	    
    }, 'json');
}
var Sidebar = {
	add_location: function (l, idx) {
	    $('<div class=""><a href="#' + idx + '" class="map-triggers" title="">' + l.name + '</a></div>').appendTo('.sidebar');
	},
	clean_locations: function () {
	    $('.sidebar').html('');
	}
}
$('.map-triggers').live('click', function () {
    //GEvent.trigger(markers[this.href.replace(/.*#/, '')], "click");
    //var old_center = map.getCenter(), old_zoom = map.getZoom();
    $(clusters).each(function () {
    	this.triggerClick(this.href.replace(/.*#/, ''));
    });
    //map.setCenter(old_center, old_zoom);
    return false;
});
$(function () {
	$('#checkboxes input').click(function () {
		var section_id = this.id.replace(/.*_/, '');
		/* if (!this.checked) { return; } */
	    $('.pagetext').load('/get-section-info?id=' + section_id);
	});
});

var awesome_interval = null;
var awesome_steps = 0;
// Due to unknown jquery + firefox + animate() issues AwesomeAnimate arises to save the day!
function awesomeAnimate(target_obj, target_pos) {
	var awesome_animation_time = 1000;
	var awesome_time_delimiter = 10;
	var awesome_step = (parseInt($(target_obj).css('left')) - parseInt(target_pos)) / (awesome_animation_time / awesome_time_delimiter);
	
	awesome_steps = 0;
	
	clearInterval(awesome_interval);
	awesome_interval = setInterval(function () {
		var new_left = (parseInt($(target_obj).css('left')) - awesome_step).toString() + 'px';
		$(target_obj).css('left', new_left);
		awesome_steps += 1;
		if (awesome_steps == (awesome_animation_time / awesome_time_delimiter)) {
			clearInterval(awesome_interval);
		}
	}, awesome_time_delimiter);
}