var iframe = false;
var map = null;
var bounds = null;
var icon = null;
var geocoder = null;
var markerIsClicked = false;
var lat = 59.913031, lng = 10.746989;
var latlngs = [];
var thumbnails = [];
var names = [];
var urls = [];
var gmarkers = [];
var img_path = STYLE_URL+'/gfx/interface/';
var marker_icon_onover = img_path + 'marker_over.png';
var marker_icon_default = img_path + 'marker_default.png';
var marker_shadow = img_path + 'marker_shadow.png';
var marker_prev;
var page; // start, search, kirke
var img_srcs = [];
var current_church_num; // defines current gallery on start page
var current_img = 1; // start page gallery image
var img_sizes = []; // amount of images in current gallery (start page)
var initialized = false; 
var addedEvent = false;
var skipMove = false; 
var churchName = null;

// =================================================================================== start page
function mapStart(loca, clearOverlay, orderChurches) {
	if(!skipMove) {
	
	if(clearOverlay) {
		skipMove = true; 	
	}
	
	clientLocation();
	
	//Set default limit om number of churches to load to 50
	var limit = "50";

	// Parse location
	if(loca != null) {
		var arra = (loca+"").split(",");
		if(arra.length == 2) {
			lat = arra[0].substring(1);
			lng = arra[1].substring(1,(arra[1]+"").length-1);
			
			if(clearOverlay != false) {
				clearMap();
			}
			
			// If we got here we succeded to find input location parameters. If so, load 100 new churches on each update.
			limit = "100"; 
		} else {
			loca = null;
		}
	}
	
	var win_location = window.location.toString();
		
	if(loca == null) {
		createMap();	
	}
			
	// remove # from url string
	//alert( win_location+'?script=mod.0073.script.get_churches&lat='+lat+'&lng='+lng);
	if(win_location.indexOf('#')!=-1) win_location = win_location.substring(0, win_location.length-1);
	showLoader();		
	$.ajax({
		url: win_location+'/?script=mod.0073.script.get_churches&limit='+limit+'&orderChurches='+orderChurches+'&lat='+lat+'&lng='+lng,
		cache: false,
		success: function(xmldoc){
			var churches = xmldoc.getElementsByTagName('church');
			var size = $(xmldoc).find('name').size();
			var _names = [], _latlngs = [], _urls = [], _thumbnails = [];
									
			$(xmldoc).find('name').each(function(){ _names.push($(this).text()) });
			$(xmldoc).find('thumbnail').each(function(){ _thumbnails.push($(this).text()) });
			$(xmldoc).find('latlng').each(function(){
				tmp_latlng = $(this).text().split(',');
				_latlngs.push(new GLatLng(tmp_latlng[0], tmp_latlng[1]));
			});
			$(xmldoc).find('url').each(function(){ _urls.push($(this).text()) });

			if(loca == null) {
				createMap();
			}

			
			for (var i = 0; i < _names.length; i++) {					
				if(!isInArray(_names[i], names)) {
					names.push(_names[i]);
					latlngs.push(_latlngs[i]);
					urls.push(_urls[i]);
					thumbnails.push(_thumbnails[i]);
			
					var marker = new GMarker(_latlngs[i], icon);
					var numm = names.length - 1;
					
					map.addOverlay(createChurchMarker(_latlngs[i], icon, numm));
				}
			}
									
			if(!addedEvent) {
				GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
  					if(initialized) {
						jQuery("#Splash").hide();	
  						var orderChurches = "normal";
  						if(newLevel <= 6) {
  							orderChurches = "random"; 
  						}
  						
  						mapStart(map.getCenter(), true, orderChurches);
  						addedEvent = true;
  					}
				});

				GEvent.addListener(map, "moveend", function() {
  					if(initialized) {
						jQuery("#Splash").hide();
  						mapStart(map.getCenter(), false);
  						addedEvent = true;
  					}
				});
			}
						
			//var church_list_html = '';
			if(clearOverlay != true) {
				for (var i = 0; i < names.length; i++) {
					if(loca == null) {
						bounds.extend(latlngs[i]);
					}
					
					// all markers set - set zoom level
					if(loca == null && (i) == names.length-1){
						// EXPAND BOUNDRIES BY 10% IN ORDER TO MAKE ICONS FIT INTO THE MAP 					
						bounds = expandBoundsByRatio(bounds, 0.1);
						map.setZoom(map.getBoundsZoomLevel(bounds));
						map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
					}
				}	
			}			
			initialized = true;
			
			hideLoader(); 
		}	

	});	
	} else {
		skipMove = false;
	}
}

function isInArray(value, arr) {
	for(var i=0; i<arr.length; i++) {
		if(arr[i] == value)
			return true; 
	}
	
	return false;
}

function clientLocation(){
	if (google.loader.ClientLocation) {
		var cl = google.loader.ClientLocation;
		// Default location
		
		//var location = [cl.address.city, cl.address.region, cl.address.country].join(', ');	 
				
		// Only use client location if user in Norway
		if(cl.address.country == "Norway"){
			lat = cl.latitude;
			lng = cl.longitude;
		}
	}
}

function mapWidget(loca, clearOverlay){
	if(!skipMove) {
	
		if(clearOverlay) {
			skipMove = true; 	
		}
		
		if(loca != null) {
			var arra = (loca+"").split(",");
			if(arra.length == 2) {
				lat = arra[0].substring(1);
				lng = arra[1].substring(1,(arra[1]+"").length-1);
				
				if(clearOverlay != false) {
					clearMap();
				}
				
			} else {
				loca = null;
			}
		}

		if(loca == null) {
			createMap();
		}

		$.ajax({
			url: URL_PREFIX+'://'+SITE_DOMAIN+'/?script=mod.0073.script.get_churches&limit=10&lat='+lat+'&lng='+lng+"&exclude="+names[0],
			cache: false,
			success: function(xmldoc){
				var churches = xmldoc.getElementsByTagName('church');
				var size = $(xmldoc).find('name').size();
				var _names = [], _latlngs = [], _urls = [], _thumbnails = [];
										
				$(xmldoc).find('name').each(function(){ _names.push($(this).text()) });
				$(xmldoc).find('thumbnail').each(function(){ _thumbnails.push($(this).text()) });
				$(xmldoc).find('latlng').each(function(){
					tmp_latlng = $(this).text().split(',');
					_latlngs.push(new GLatLng(tmp_latlng[0], tmp_latlng[1]));
				});
				$(xmldoc).find('url').each(function(){ _urls.push($(this).text()) });
			
				icon.image = marker_icon_default;
				
				//SKip the first church wich has already been added with special icon						
				for (var i = 1; i < _names.length; i++) {		
					if(!isInArray(_latlngs[i], latlngs)) {			
						names.push(_names[i]);
						latlngs.push(_latlngs[i]);
						urls.push(_urls[i]);
						thumbnails.push(_thumbnails[i]);
						
						var numm = names.length-1;
						
						map.addOverlay(createChurchMarker(_latlngs[i], icon, numm));
					}
				}
						
				if(!addedEvent) {
					GEvent.addListener(map, "zoomend", function() {
	  					if(initialized) {
	  						mapKirke(map.getCenter(), false);
	  						addedEvent = true;
	  					}
					});
	
					GEvent.addListener(map, "moveend", function() {
	  					if(initialized) {
	  						mapKirke(map.getCenter(), false);
	  						addedEvent = true;
	  					}
					});
				}
	
							
				//var church_list_html = '';
				if(loca == null && clearOverlay != true) {
					for (var i = 0; i < latlngs.length; i++) {
						// Extend the bounds object
						bounds.extend(latlngs[i]);
						
						// all markers set - set zoom level
						if((i) == names.length-1){
							// EXPAND BOUNDRIES BY 10% IN ORDER TO MAKE ICONS FIT INTO THE MAP 
							bounds = expandBoundsByRatio(bounds, 0.1);
                 			map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
						}
					}	
				}
													
				initialized = true; 
			}	
					
		});	
	} else {
		skipMove = false;
	}
}

function mapKirke(loca, clearOverlay){
	if(!skipMove) {
	
		if(clearOverlay) {
			skipMove = true; 	
		}
		
		if(loca != null) {
			var arra = (loca+"").split(",");
			if(arra.length == 2) {
				lat = arra[0].substring(1);
				lng = arra[1].substring(1,(arra[1]+"").length-1);
				
				if(clearOverlay != false) {
					clearMap();
				}
				
			} else {
				loca = null;
			}
		}

		if(loca == null) {
			createMap();
		}

		$.ajax({
			url: URL_PREFIX+'://'+SITE_DOMAIN+'/?script=mod.0073.script.get_churches&limit=10&lat='+lat+'&lng='+lng+"&exclude="+names[0],
			cache: false,
			success: function(xmldoc){
				var churches = xmldoc.getElementsByTagName('church');
				var size = $(xmldoc).find('name').size();
				var _names = [], _latlngs = [], _urls = [], _thumbnails = [];
										
				$(xmldoc).find('name').each(function(){ _names.push($(this).text()) });
				$(xmldoc).find('thumbnail').each(function(){ _thumbnails.push($(this).text()) });
				$(xmldoc).find('latlng').each(function(){
					tmp_latlng = $(this).text().split(',');
					_latlngs.push(new GLatLng(tmp_latlng[0], tmp_latlng[1]));
				});
				$(xmldoc).find('url').each(function(){ _urls.push($(this).text()) });
			
				icon.image = marker_icon_default;
				
				//SKip the first church wich has already been added with special icon						
				for (var i = 1; i < _names.length; i++) {		
					if(!isInArray(_latlngs[i], latlngs)) {			
						names.push(_names[i]);
						latlngs.push(_latlngs[i]);
						urls.push(_urls[i]);
						thumbnails.push(_thumbnails[i]);
						
						var numm = names.length-1;
						
						map.addOverlay(createChurchMarker(_latlngs[i], icon, numm));
					}
				}
						
				if(!addedEvent) {
					GEvent.addListener(map, "zoomend", function() {
	  					if(initialized) {
	  						mapKirke(map.getCenter(), false);
	  						addedEvent = true;
	  					}
					});
	
					GEvent.addListener(map, "moveend", function() {
	  					if(initialized) {
	  						mapKirke(map.getCenter(), false);
	  						addedEvent = true;
	  					}
					});
				}
	
							
				//var church_list_html = '';
				if(loca == null && clearOverlay != true) {
					for (var i = 0; i < latlngs.length; i++) {
						// Extend the bounds object
						bounds.extend(latlngs[i]);
						
						// all markers set - set zoom level
						if((i) == names.length-1){
							// EXPAND BOUNDRIES BY 10% IN ORDER TO MAKE ICONS FIT INTO THE MAP 
							bounds = expandBoundsByRatio(bounds, 0.1);
                 			map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
						}
					}	
				}
													
				initialized = true; 
			}	
					
		});	
	} else {
		skipMove = false;
	}
}

// =================================================================================== search page
function mapSearch(){	
	createMap();

	function createMarker(latlng, num) {
		var marker = new GMarker(latlng, icon);
		
		// click
		GEvent.addListener(marker, "click", function() {
			floatingWindow('click', num, marker);
		});
		$('#SearchResult li:eq('+ num +')').click(function(){
			floatingWindow('click', num, marker);
		})
		
		// mouseover
		GEvent.addListener(marker, "mouseover", function() {
			floatingWindow('mouseover', num, marker);
		})
		$('#SearchResult li:eq('+ num +')').mouseover(function(){
			floatingWindow('mouseover', num, marker);
		})
		
		// mouseout
		GEvent.addListener(marker, "mouseout", function() {
			floatingWindow('mouseout', num, marker);
		})
		$('#SearchResult li:eq('+ num +')').mouseout(function(){
			floatingWindow('mouseout', num, marker);
		})
		
		return marker;
	}
		
	for (var i = 0; i < lats.length; i++) {
		var latlng = new GLatLng(lats[i], lngs[i]); 
		latlngs.push(latlng);
		var marker = createMarker(latlng, i);
		map.addOverlay(marker);
		bounds.extend(latlng);
		
         // make 10% bigger so all markers show completely
         //var span = new GSize((bounds.maxX - bounds.minX) * 1.1,
         //        (bounds.maxY - bounds.minY) * 1.1);
         //var center = new GPoint(bounds.minX + span.width / 2.,
         //        bounds.minY + span.height / 2.); 				 
	}	

	// EXPAND BOUNDRIES BY 10% IN ORDER TO MAKE ICONS FIT INTO THE MAP 
	bounds = expandBoundsByRatio(bounds, 0.1);
		
	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function expandBoundsByRatio(bounds, ratio) {
         // initialize bounds to be the same as original
         var largerBounds = new GLatLngBounds(
             bounds.getSouthWest(), bounds.getNorthEast());
         // get lat, lng of north east and south west
         var northEastLat = bounds.getNorthEast().lat();
         var northEastLng = bounds.getNorthEast().lng();
         var southWestLat = bounds.getSouthWest().lat();
         var southWestLng = bounds.getSouthWest().lng();
         var diffLat = northEastLat - southWestLat;
         var diffLng = northEastLng - southWestLng;
         // multiply with ratio
         northEastLat += diffLat * ratio;
         southWestLat -= diffLat * ratio;
         northEastLng += diffLng * ratio;
         southWestLng -= diffLng * ratio;
         // extend north east
         largerBounds.extend(new GLatLng(northEastLat, northEastLng));
         // extend south west
         largerBounds.extend(new GLatLng(southWestLat, southWestLng));
         
         return largerBounds;
} 


// =================================================================================== global

function createMap(){
	latlngs = [];
	thumbnails = [];
	names = [];
	urls = [];		
	gmarkers = [];	

	map = new GMap2(document.getElementById("Map"));
	map.setMapType(G_PHYSICAL_MAP);
	
	icon = new GIcon();
	icon.image = (page=='kirke') ? marker_icon_onover : marker_icon_default;
	icon.shadow = marker_shadow;
	icon.iconSize = new GSize(20, 42);
	icon.shadowSize = new GSize(35, 42); 
	icon.iconAnchor = new GPoint(10, 42);
	
	switch(page){
	
		case 'start':
			var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
			map.addControl(new GSmallMapControl(), topRight);
			var ovmap = new GOverviewMapControl(new GSize(150,230)); 
			map.addControl(ovmap);
			//setTimeout("ovmap.setZoom(3);",1); 		
		break;
		
		case 'search':
			map.addControl(new GSmallMapControl());
			lat = lats[0];
			lng = lngs[0];
		break
		
		case 'kirke':
			var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
			map.addControl(new GSmallMapControl(), topRight);
			var latlng = new GLatLng(lat, lng);
			latlngs.push(latlng);
			names.push(churchName);
			urls.push("");
			thumbnails.push("");
			map.addOverlay(createChurchMarker(latlng, icon, names.length-1));
		break;
	}
	
	map.setCenter(new GLatLng(lat, lng), 1);
	map.setZoom(7);
	bounds = new GLatLngBounds();
}


// creates a info window with church name and place it over marker
function floatingWindow(evt, num, marker){
	removeFloatingWindow(marker, num);

	// rollover marker
	if(evt == 'mouseover'){
		// marker position
		var posX = map.fromLatLngToContainerPixel(latlngs[num]).x;
		var posY = map.fromLatLngToContainerPixel(latlngs[num]).y;


		// church name
		var name;
		if(page == 'start'){
			name = names[num];
			//$('#ChurchList a:eq('+ num +')').css('color','#999');
		}else if(page == 'search'){
			name = $('#SearchResult li:eq('+ num +') h3').text();
			// highligth church in result list
			$('#SearchResult li:eq('+ num +') h3:first').css('text-decoration','underline');
			$('#SearchResult li:eq('+ num +') #Img').css('border-color','black');
		} else {
			name = names[num];		
			//alert(name);
		}
			
		var markerHTML = '';
		
		if(thumbnails[num] != null && thumbnails[num] != "") {
			markerHTML += '<div id="MarkerWin"><div class="bubbleTop"><div style="width: 103px;"><img style="margin-top: 8px; margin-bottom: 5px;" width="84" height="84" src="'+thumbnails[num]+'" /><div style="text-align: center;" class="p bold white">'+ name +'</div></div></div><div class="bubbleBottom"></div></div>';			
		} else {
			markerHTML += '<div id="MarkerWin">';
			markerHTML +=		'<div id="Text">';
			markerHTML +=			'<div class="edge" style="background:url('+ img_path +'floatwin_left.png)"></div>';
			markerHTML +=			'<div id="Middle" class="p bold white" style="background:url('+ img_path +'floatwin_middle.png) repeat-x;">'+ name +'</div>';
			markerHTML +=			'<div class="edge" style="background:url('+ img_path +'floatwin_right.png)"></div>';
			markerHTML +=		'</div>';
			markerHTML +=		'<div id="Tail" style="background:url('+ img_path +'floatwin_tail.png) no-repeat center;"></div>';
			markerHTML +=	'</div>';
		}
		
		if(thumbnails[num] != null && thumbnails[num] != "") {
			// create info window
			$('#Map').append(markerHTML);
			var cssObj = {
				'top':posY-175
			} 
			$('#MarkerWin')	.css(cssObj)
							.css('left',(posX-($('#MarkerWin').width()/2)-25));
		} else {
			// create info window
			$('#Map').append(markerHTML);
			var cssObj = {
				'top':posY-79
			} 
			$('#MarkerWin')	.css(cssObj)
							.css('left',(posX-($('#MarkerWin').width()/2)-(25)));
			
			if(posX + ($('#MarkerWin').width()/2) > $('#Map').width()) {
				var post = $('#MarkerWin').position();
				$('#MarkerWin')	.css(cssObj)
								.css('left', (posX-($('#MarkerWin').width()/2)+25-($('#MarkerWin').width())));
				$('#MarkerWin')	.css(cssObj).css("backgroundPosition", "0px 10px");								
			}		
		}
		
		// if marker outside #Map - remove float window!
		var outsideMap = false;
		if(posX < 0) outsideMap = true;
		if(posX > $('#Map').width()) outsideMap = true;
		if(posY < 0) outsideMap = true;
		if(posY > $('#Map').height()) outsideMap = true;
		if(outsideMap) $('#MarkerWin').remove();
		
		// marker image
		marker.setImage(marker_icon_onover);

	// click marker
	}else if(evt == 'click'){
		window.location = $('#SearchResult li:eq('+ num +') #href').val();
	}else if(evt == 'mouseout'){
		// search result
		$('#SearchResult li:eq('+ num +') #Img').css('border-color','#ccc');	
	}
}

// Creates a marker at the given point
function createChurchMarker(latlng, icon, num) {
	var marker = new GMarker(latlng, icon);

	GEvent.addListener(marker, 'click', function() {
		if(iframe)
			window.open(urls[num],"","status=yes,toolbar=yes,menubar=yes,resizable=yes");
		else
			window.location = urls[num];
	});
	GEvent.addListener(marker, 'mouseover', function() {
		floatingWindow('mouseover', num, marker);
	})
	GEvent.addListener(marker, 'mouseout', function() {
		floatingWindow('mouseout', num, marker);
	})
	
	return marker;
}

function clearMap() {
	map.clearOverlays();
	latlngs = [];
	urls = [];
	thumbnails = [];
	names = [];
	gmarkers = [];
}

function showLoader() {
	var position = $("#Map").offset();
	jQuery("#loaderContainer").css(position);
	jQuery("#loaderContainer").css('margin-left', $("#Map").width()/2 - jQuery("#loaderContainer").width()/2);	
	jQuery("#loaderContainer").css('margin-top', $("#Map").height()/2 - jQuery("#loaderContainer").height()/2);	
	jQuery("#loaderContainer").show();	
}

function hideLoader() {
	jQuery("#loaderContainer").hide();
}

function removeFloatingWindow(marker, num){
	// remove floating window
	$('#MarkerWin').remove();
	$('#SearchResult li:eq('+ num +') h3:first').css('text-decoration','none');
	
	// marker image
	if((marker && churchName == null) || (churchName != null &&  num > 0)) marker.setImage(marker_icon_default);
	if(page == 'start') $('#ChurchList a:eq('+ num +')').css('color','white');
}