var map;
var mapLoaded = false;
var mapCenter = {lat:52.516412, lng:13.402964}; //default value
var mapDragging = false;
var ajaxSpinnerPath = baseURL + 'wp-content/themes/berlin_ip_map/images/ajax_loader.gif';
var localMode = false;
var ajaxLoading = false;

function loadMap() {	
	if (GBrowserIsCompatible() && !mapLoaded) {
		resizeWindow(null);
		map = new GMap2(document.getElementById("map"));
    	map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lng), 19, G_SATELLITE_MAP);
    	mapLoaded = true;
 	}
 	if(!localMode) {
 		GEvent.addListener(map, "movestart", function() { mapDragging = true; });
 		GEvent.addListener(map, "moveend", mapMoved);
 	}
}

function resizeWindow(event) {
	if(($("#content-container").height() + 200) > $(window).height()) {
		$("#map").height($("#content-container").height() + 200);
	} else {
		$("#map").height($(window).height());
	}
}

function mapMoved() {
	var center = map.getCenter();
	$.ajax({
   		type: "POST",
	    url: baseURL + "mmomap/set_map_location.php",
   		data: "lat=" + center.lat() + "&lng=" + center.lng(),
   		success: function(msg){
     		mapDragging = false;
   		},
   		error: function(XMLHttpRequest, textStatus, errorThrown) {
   			//alert('error');
   		}
 	});
}

// This function is called:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser	
function loadContent(hash) {
	if(!ajaxLoading) { // hack to prevent double calling of loadContent in FF
		ajaxLoading = true;
		//alert('loading...' + hash);
		var height = $('#content-container .i3').height() - 20;
		$('#content').height(height); // preserve height while showing spinner
		$('#content').html('<img src="' + ajaxSpinnerPath + '"/>');
		
		$.get(baseURL + hash, {ajax:1}, function(data) { 
			$('#content').css('height', ''); // remove hight style
			$('#content').html(data); 
			//alert(data);
			resetContentEvents();
		});
	}
}

function resetContentEvents() {
	// set onlick event for buttons	
	$("#content a[rel='history'], .navigation a").unbind("click").click(function(){
		// generate hash from standard url
		var hash = this.href.slice(baseURL.length, this.href.length);
		//alert('going to load ' + hash);
		$.historyLoad(hash);
		return false;
	});
	// Attach slider action to discussion
	$('#discussion').hide();
	$('#discussion-toggle').unbind("click").click(function() {
		$('#discussion').slideToggle('slow', function() {
			resizeWindow();
		});
	});	

	resizeWindow();
	ajaxLoading = false;
}

// Simple jQuery Slideshow
// By <a href="http://jonraasch.com/blog/">Jon Raasch</a>
function slideSwitch() {
	if($('#slideshow').html()) {
		//alert('foo');
		
		var $active = $('#slideshow IMG.active');	
		if ($active.length == 0) $active = $('#slideshow IMG:last');
	
		// use this to pull the images in the order they appear in the markup
		var $next =  $active.next().next().length ? $active.next().next()
			: $('#slideshow IMG:first');
		// get next.next sibling, because WP inserts br/ after each image
	
		// uncomment the 3 lines below to pull the images in random order
		
		// var $sibs  = $active.siblings();
		// var rndNum = Math.floor(Math.random() * $sibs.length );
		// var $next  = $( $sibs[ rndNum ] );
	
		$active.addClass('last-active').animate({opacity: 0.0}, 500);
	
		$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 500, function() {
				$active.removeClass('active last-active');
			}
		);
	}
}

function reloadSidebar(language) {
	$.get(baseURL + language, {sidebar_ajax:1}, function(data) { 
		$('#sidebar').html(data);
		setTimeout("resetSidebarEvents();", 500); 
	});
}

function resetSidebarEvents() {
	$("#sidebar a[rel='history']").unbind("click").click(function(){
		// generate hash from standard url
		var hash = this.href.slice(baseURL.length, this.href.length);
		//alert('going to load ' + hash);
		$.historyLoad(hash);
		return false;
	});

	// Attach slider action to portfolio
	$('#portfolio-toggle').click(function() {
		$('#portfolio-submenu').slideToggle('fast');
	});	
		
	// Hijax search form submit
    $('#searchform').submit(function() {
    	//alert('going to search');
    	var currentLanguage = document.location.hash.slice(1, 4);
    	if(currentLanguage != 'de/') currentLanguage = '';
    	if($('#s'))	$.historyLoad(currentLanguage + '?s=' + $('#s').val());
    	return false;
    });  

	// Hijax qtrans language chooser, quick hack for current setup (two possible languages / and /de/)
	$('#qtrans_select_qtranslate-chooser').unbind("change").change(function() {
		// jeweils entweder '' oder 'de/'
		var currentLanguage = document.location.hash.slice(1, 4);
		var selectedLanguage = this.value.slice(baseURL.length, baseURL.length + 3);
		if(selectedLanguage != 'de/') selectedLanguage = '';
		//alert(currentLanguage + '->' + selectedLanguage);
		var hash, newHash;
		if(currentLanguage == 'de/' && selectedLanguage != 'de/') {
			newHash = document.location.hash.slice(4, document.location.hash.length);		
		} else if(currentLanguage != 'de/' && selectedLanguage == 'de/') {
			hash = document.location.hash.slice(1, document.location.hash.length);		
			newHash = selectedLanguage + hash;			
		}
		//alert(newHash);
		if(typeof(newHash) != 'undefined') {
			$.historyLoad(newHash);
			reloadSidebar(selectedLanguage);
		}
		return false;
	});
	
	// Remove 'SEARCH' when clicking into search form
	$('#s').click(function() {
		if($('#s').val() == 'SEARCH' || $('#s').val() == 'SUCHEN') { 
			$('#s').val(''); 
		}
	});
	
	// Restore 'SEARCH' in search form
	var currentLanguage = document.location.hash.slice(1, 4);
    if(currentLanguage == 'de/') {
		$('#s').val('SUCHEN');    
    } else {
    	$('#s').val('SEARCH');
    }
	$('#s').blur();
}

$(document).ready(function() {
	cbb.init();

	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(loadContent);
	resetContentEvents();
	if(document.location.hash.slice(1, 4) == 'de/') {		
		reloadSidebar('de/');
	} else {
		resetSidebarEvents();
	}
	
	$(window).resize(resizeWindow);
	$(window).unload(function() { 
		GUnload(); 
	});
	
	// Reload page when clicking on logo
	$('#header').click(function() {	
		$.historyLoad('');
	});
	
	if(!localMode) {
		mapCenter.lat = $('meta[name=lat]').attr("content"); 
		mapCenter.lng = $('meta[name=lng]').attr("content"); 
	}
	loadMap();
	
	if(!localMode) {
		$.PeriodicalUpdater({
      		url : baseURL + "mmomap/get_map_location_json.php",
      		method: "GET",
      		type: "json",
      		minTimeout: 5000,
      		maxTimeout: 10000
   		},
   		function(data) {
			mapCenter = data;
			if(!mapLoaded) loadMap();
			else {
				if(!mapDragging) 
					map.panTo(new GLatLng(mapCenter.lat, mapCenter.lng));
			}
		});
	}
	
	setInterval( "slideSwitch()", 5000 );
});