var tooltip;
var panoClient;
var panoView;
var directions;
var streetViewNotAvailableList = new Array();

var isLocationSwapped=false;
// Compute the intersection of n arrays
Array.prototype.intersectWeak =
function() {
	if (!arguments.length)
		return [];
	var a1 = this;
	var a = a2 = null;
	var n = 0;
	while (n < arguments.length) {
		a = [];
		a2 = arguments[n];
		var l = a1.length;
		var l2 = a2.length;
		for (var i = 0; i < l; i++) {
			for (var j = 0; j < l2; j++) {
				if (a1[i] == a2[j])
					a.push(a1[i]);
			}
		}
		a1 = a;
		n++;
	}
	return a;
};

Array.prototype.findAll =
function(booleanClosure) {
	var sourceArray = this;
	var retArray = new Array();
	for (i = 0; i < sourceArray.length; i++) {
		if (booleanClosure(sourceArray[i])) {
			retArray.push(sourceArray[i])
		}
	}
	return retArray.length ? retArray : null;
};

Array.prototype.find =
function(booleanClosure) {
	var result = this.findAll(booleanClosure);
	return result ? result[0] : null;
};

function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(), map.getZoom());
	var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), map.getZoom());
	var anchor = marker.getIcon().iconAnchor;
	var width = marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width, - offset.y + point.y + anchor.y));
	pos.apply(tooltip);
	tooltip.style.visibility = "visible";
}

// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
function mymouseover(i) {
	showTooltip(gmarkers[i])
}
// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
function mymouseout() {
	tooltip.style.visibility = "hidden";
}

function createMarker(lng, lat, text, url, iconType) {

	var icon = new GIcon(G_DEFAULT_ICON);

	if (iconType == 'cluster') {
		icon.iconSize = new GSize(10, 17);
		icon.iconAnchor = new GPoint(5, 17);
		icon.image = '/images/map-marker-small.png';
		icon.shadow = "";
	} else if (iconType == 'guide') {
		icon = new GIcon(G_DEFAULT_ICON);
		icon.image = '/images/information/information.png';
		icon.iconSize = new GSize(29, 36);
		icon.iconAnchor = new GPoint(12, 36);
		icon.shadow = "";
	} else if (iconType == 'symbol') {
		icon = new GIcon(G_DEFAULT_ICON);
		icon.image = '/images/dot9red.gif';
		icon.iconSize = new GSize(9, 9);
		icon.iconAnchor = new GPoint(4, 4);
		icon.shadow = "";
	}
	var opts = {
		"icon": icon,
		clickable: true
	};
	var latlng = new GLatLng(lat, lng);
	var marker = new GMarker(latlng, opts);

	if (text != undefined) {

		marker.tooltip = '<div class="tooltip">' + text + '</div>';

		GEvent.addListener(marker, "mouseover", function() {
			showTooltip(marker);
		});
		GEvent.addListener(marker, "mouseout", function() {
			tooltip.style.visibility = "hidden"
		});

		GEvent.addListener(marker, "click", function() {
			var myHtml = "<br/><a href='" + url + "'>" + text + "</a>";
			map.openInfoWindowHtml(latlng, myHtml);
		});
	}

	return marker;

}


function createSymbolMarker(symbol, infoWindow, selectedCategories) {

	if (infoWindow == undefined)
		infoWindow = true;

	if (selectedCategories == undefined)
		selectedCategories = new Array(0);

	//jQuery.inArray(value, array)
	//console.log(selectedCategories);
	//console.log(symbol.categories);

	var icon = new GIcon(G_DEFAULT_ICON);

	if (map.getZoom() >= 8) {

		var categoryToShow = symbol.categoryName;

		var categoriesToChooseIconFrom = selectedCategories.intersectWeak(symbol.categories);
		var iconOkToShow = jQuery.inArray(symbol.categoryId.toString(), categoriesToChooseIconFrom) != -1;
		if (!iconOkToShow) {
			categoryToShow = categoryNames[categoriesToChooseIconFrom[0]]
		}

		if (symbol.categories.length > 1) {
			icon.image = '/images/symbol-categories-2/' + categoryToShow + '_plus.png';
		} else {
			icon.image = '/images/symbol-categories-2/' + categoryToShow + '.png';
		}
		icon.iconSize = new GSize(29, 36);
		icon.iconAnchor = new GPoint(11, 36);
	} else {
		icon.image = '/images/dots/dot2.png';
		icon.iconSize = new GSize(10, 9);
		icon.iconAnchor = new GPoint(5, 5);
	}

	icon.shadow = "";

	var opts = {
		icon: icon,
		zIndexProcess: function(m, x) {
			//return m.getPoint().lat() + 1000;
			return 1000;
		}
	};
	var latlng = new GLatLng(symbol.latitude, symbol.longitude);
	var marker = new GMarker(latlng, opts);

	marker.tooltip = '<div class="tooltip">' + symbol.name + '</div>';

	GEvent.addListener(marker, "mouseover", function() {
		_gaq.push(['_trackEvent', 'Map', 'Tooltip', 'Symbol: ' + symbol.name]);
		showTooltip(marker);
	});
	GEvent.addListener(marker, "mouseout", function() {
		tooltip.style.visibility = "hidden"
	});

	if (infoWindow) {
		GEvent.addListener(marker, "click", function() {
			var myHtml = "";
			var symbolUrl = "";
			var symbolTarget = "";
			var attributesToBeAddedToLink = '';
			if (symbol.url != undefined && symbol.url.length > 0) {
				symbolTarget = "_blank";
				symbolUrl = symbol.url;
				attributesToBeAddedToLink = " class='symbolLink' onclick='updateSymbolCounters(" + symbol.id + ")'"
			} else {
				symbolUrl = "/symbol/info/" + symbol.id;
			}

			myHtml = "<b>" + symbol.name + "</b><br/><a target='" + symbolTarget + "' href='" + symbolUrl + "'" + attributesToBeAddedToLink + ">" + msgs['map.tooltip.readMore'] + "</a>";
			if(typeof isStartPage != 'undefined'){
				myHtml += " | <a href='#' onclick='showDirectionForLatLng(\""+symbol.name+"\"," + symbol.latitude + "," + symbol.longitude + ");return false;'>" + msgs['directions.title'] + "</a>";
				if (streetViewNotAvailableList.find(function(obj) {
					return obj['latitude'] == symbol.latitude && obj['longitude'] == symbol.longitude
				})) {
					myHtml += " | <span style='color:red;'>" + msgs['streetView.notAvailable'] + "</span><br/>";
				} else {
					myHtml += " | <a href='#' onclick='showStreetView(" + symbol.latitude + "," + symbol.longitude + ", this);'>" + msgs['streetView.title'] + "</a><br/>";
				}
			}else{
				myHtml+="<br/>";
			}
			jQuery.each(symbol.categories, function(idx, elem) {
				myHtml += "<img style='padding-top: 8px;' src='/images/symbol-categories-2/" + categoryNames[elem] + "_round.png' title='" + categoryLocalNames[elem] + "' alt='" + categoryLocalNames[elem] + "' />"
			});

			_gaq.push(['_trackEvent', 'Map', 'InfoWindow', 'Symbol: ' + symbol.name]);
			map.openInfoWindowHtml(latlng, myHtml);
		});
	}

	return marker;

}


jQuery(function() {
	jQuery('#spinner')
			.hide()// hide it initially
			.ajaxStart(function() {
		jQuery(this).show();
	})
			.ajaxStop(function() {
		jQuery(this).hide();
	})
			;


	jQuery('.blink')
			.focus(function() {
		if (jQuery(this).attr('value') == jQuery(this).attr('title')) {
			jQuery(this).attr({ 'value': '' })
		}
	})
			.blur(function() {
		if (jQuery(this).attr('value') == '') {
			jQuery(this).attr({ 'value': jQuery(this).attr('title') })
		}
	})


});


function search(query) {

	if (window.isStartPage === undefined) {
		document.location = "/#query:" + query;
	} else {

        jQuery("#map-overlay").hide();

		_gaq.push(['_trackEvent', 'Map', 'Search', query]);

		//  changed 2010-11-03 to not use these 2 parameters
		//    geocoder.setViewport(map.getBounds());
		//    geocoder.setBaseCountryCode("se");

		geocoder.getLocations(
				query,
												 function(result) {
													 if (result.Status.code == G_GEO_SUCCESS) {

														 var box = result.Placemark[0].ExtendedData.LatLonBox;
														 var bounds = new GLatLngBounds(new GLatLng(box.south, box.west), new GLatLng(box.north, box.east));
														 var center = new GLatLng(result.Placemark[0].Point.coordinates[1], result.Placemark[0].Point.coordinates[0]);
														 var zoom = map.getBoundsZoomLevel(bounds);
														 map.setCenter(center, zoom);

														 if (searchPin != undefined) {
															 map.removeOverlay(searchPin);
														 }

														 var icon = new GIcon(G_DEFAULT_ICON);
														 icon.image = '/images/position.png';
														 icon.iconSize = new GSize(19, 19);
														 icon.iconAnchor = new GPoint(9, 9);
														 icon.shadow = "";
														 var opts = {
															 icon: icon
														 }
														 searchPin = new GMarker(center, opts);


														 map.addOverlay(searchPin);

													 } else {
														 alert(query + " " + msgs['map.search.notFound'] + ".");
													 }
												 }
				);

	}
}

function updateRegions1ForGuide(data) {
	var rselect = document.getElementById('region1.id')

	// Clear all previous region1
	var l = rselect.length

	while (l > 0) {
		l--;
		rselect.remove(l);
	}

	// Clear all previous region2

	var region2s = document.getElementById('region2.id')

	l = region2s.length;

	while (l > 0) {
		l--;
		region2s.remove(l)
	}


	for (var i = 0; i < data.length; i++) {
		var region = data[i]
		var opt = document.createElement('option');
		opt.text = region.name;
		opt.value = region.id;
		try {
			rselect.add(opt, null) // standards compliant; doesn't work in IE
		}
		catch(ex) {
			rselect.add(opt) // IE only
		}
	}
	if (data.length > 0) {
		jQuery.get('/region/ajaxGetRegions2', { 'region1': data[0].id, 'country':$('country.id').value }, updateRegions2ForGuide, 'json')
	} else {
		updateRegions2ForGuide([]);
	}
}

function updateRegions2ForGuide(data) {
	var rselect = document.getElementById('region2.id')

	// Clear all previous options
	var l = rselect.length

	while (l > 0) {
		l--
		rselect.remove(l)
	}

	for (var i = 0; i < data.length; i++) {
		var region = data[i]
		var opt = document.createElement('option');
		opt.text = region.name
		opt.value = region.id
		try {
			rselect.add(opt, null) // standards compliant; doesn't work in IE
		}
		catch(ex) {
			rselect.add(opt) // IE only
		}
	}
}

function debugStatement(msg) {
	if (typeof(console) != 'undefined') {
		console.debug(msg);
	}
}

function updateSymbolCounters(symbolId) {
	jQuery.get("/symbol/updateSymbolClickCounter/" + symbolId, function (data) {
	});
	return true;
}

function initAutoComplete(inputElementId, lang, callback) {
	var geocoder = new google.maps.Geocoder();
	jQuery("#" + inputElementId).geo_autocomplete(geocoder, {
		selectFirst: false,
		minChars: 3,
		cacheLength: 50,
		width: 356,
		scroll: true,
		scrollHeight: 330,
		language:lang
	}).result(function(_event, _data) {
		if (callback) {
			callback(_event, _data);
		}
	});
}

function handleNoFlash(errorCode) {
	if (errorCode == 603) {
		alert(msgs['streetView.browser.notSupported']);
	}
}


function showStreetView(lat, lon, anchor) {
	var latLng = new GLatLng(lat, lon); //new GLatLng(42.345573,-71.098326);
	if (!panoClient) {
		panoClient = new GStreetviewClient();
	}
	panoClient.getNearestPanorama(latLng, function(panoData) {
		if (panoData.code != 200) {
			streetViewNotAvailableList.push({'latitude':lat, 'longitude':lon});
			jQuery(anchor).replaceWith("<span style='color:red;'>" + msgs['streetView.notAvailable'] + "</span><br/>");
			map.updateInfoWindow();
		} else {
			showPanoView(panoData);
		}
	});
	return false;
}

function hideStreetView() {
	jQuery('#pano_canvas-outer').hide();
	jQuery('#map_canvas').show();
	jQuery('#map-accordion').show();
	if(panoView){
		panoView.remove();
	}
	map.checkResize();
}

function showPanoView(panoData) {
	panoView = new GStreetviewPanorama(document.getElementById("pano_canvas"));
	GEvent.addListener(panoView, "error", handleNoFlash);
	jQuery('#map-accordion').hide();
	jQuery('#map_canvas').hide();
	jQuery('#pano_canvas-outer').show();
	panoView.setLocationAndPOV(panoData.location.latlng);
}

function swapLocations(){
	isLocationSwapped=!isLocationSwapped;
	var fromLocationSpanHtml=jQuery('#fromLocationSpan').html();
	var toLocationSpanHtml=jQuery('#toLocationSpan').html();
	jQuery('#fromLocationSpan').html(toLocationSpanHtml);
	jQuery('#toLocationSpan').html(fromLocationSpanHtml);
	jQuery("#fromLocationTextField").val(jQuery('#fromLocation').val());
	initAutoComplete('fromLocationTextField', lang, function(e,d){jQuery('#fromLocation').val(jQuery('#fromLocationTextField').val());});

	updateDirectionOnMap();
}

function showDirectionForLatLng(symbolName, lat, lng) {
	showDirectionOnMap(symbolName, lat + "," + lng);
}

function updateDirectionOnMap() {
	showDirectionOnMap(jQuery('#toLocationTextField').text(), jQuery('#toLocation').val());
}

function showDirectionOnMap(symbolName, toLocation) {
	jQuery('#route_form').show();
	jQuery('#toLocation').val(toLocation);
	jQuery('#toLocationTextField').text(symbolName);
	var fromLocation = jQuery('#fromLocation').val();
	if (fromLocation.length < 1) {
		jQuery("#fromLocationTextField").focus();
	} else {
		var locationString =isLocationSwapped?"from: " + toLocation+ " to: " + fromLocation :"from: " + fromLocation + " to: " + toLocation;
		if (!directions) {
			directionsPanel = document.getElementById("route");
			directions = new GDirections(map, directionsPanel);
		}
		isDirectionViewVisible=true;
		jQuery('#map-accordion').hide();
		map.closeInfoWindow();
		mgr.clearMarkers();
		directions.load(locationString);
	}
}

function hideDirections() {
	if (directions) {
		directions.clear();
		map.closeInfoWindow();
		isDirectionViewVisible=false;
		jQuery('#map-accordion').show();
		updateSymbols();
	}
	jQuery('#route_form').hide();
}
function ajaxFileUpload(url) {
	var language = jQuery("#language").val();
	var guideObjectId = jQuery("#guideObjectId").val();
	jQuery.ajaxFileUpload
			(
			{
				url:url,
				secureuri:false,
				fileElementId:'fileToUpload',
				params :{
					guideObjectId:guideObjectId,
					language: language
				},
				dataType: 'update',
				divToBeUpdated:'#guideObjectsList',
				success: function (data, status) {
					if (typeof(data.error) != 'undefined') {
						if (data.error != '') {
							debugStatement(data.error);
						} else {
							debugStatement(data.msg);
						}
					}
					debugStatement(data);

					//						$('#uploadedFileSize').attr('src', data);
				},
				error: function (data, status, e) {
					debugStatement(e);
				},
				complete: function(data, status) {
					hideForm();
				}
			}
					);

	return false;

}
function showGuideObjectForm() {
	jQuery("#guideObjectForm").show();
	jQuery("#addGuideObjectLink").hide();
	return false;
}

function hideForm() {
	jQuery("#guideObjectForm").hide();
	jQuery("#addGuideObjectLink").show();
	jQuery("#fileToUpload").val("");
	jQuery("#language")[0].selectedIndex = 0;
	return false;
}
function  editGuideObject(guideObjectId,language) {
	jQuery("#guideObjectForm").show();
	jQuery("#addGuideObjectLink").hide();
	jQuery("#guideObjectId").val(guideObjectId);
	jQuery("#language").val(language.toUpperCase());
	return false;
}
function deleteGuideObject(url, guideObjectId) {
	jQuery.post(url, {guideObjectId:guideObjectId}, function(data) {

	});
	jQuery("#guideObject-" + guideObjectId).remove();
	return false;
}

function checkAuthority() {
	if (jQuery('#authorities').val()) {
		jQuery('#authoritiesFlash').empty()
	} else {
		jQuery('#authoritiesFlash').text(msgs['role.notSelected']);
	}
	return jQuery('#authorities').val() != null;
}

function checkRepeatPassword(){
	if (jQuery('input[name=passwd]').val()!=jQuery('#passwdRepeat').val()) {
		jQuery('#passwdRepeatFlash').text(msgs['confirmPassword.notMatch']);
	} else {
		jQuery('#passwdRepeatFlash').empty()
	}
	return jQuery('input[name=passwd]').val()==jQuery('#passwdRepeat').val()
}

function checkProfileForm(){
 return checkAuthority() && checkRepeatPassword();
}

function searchQuery(){
	search(jQuery('#query').val());
	jQuery('#fromLocation').val(jQuery('#query').val());
	jQuery('#fromLocationTextField').val(jQuery('#query').val());
	jQuery('#toLocation').val("");
	jQuery('#toLocationTextField').val("");
	hideStreetView();
	hideDirections();
}

function showFormDialogInFancyBox(guideObjectId) {
	var dialogSelector='#map-order-div';
	var fieldToBeFocusedSelector='#name';
	var existingHtml=jQuery(dialogSelector).html();
	jQuery.fancybox({
		autoDimensions:true,
		width:400,
		height:190,
		'padding'		: 5,
		disableNavButtons 	: 	true,
		'scrolling'		: 'no',
		'content': jQuery('#map-order-div').html(),
		onComplete:function() {
			jQuery(fieldToBeFocusedSelector).focus();
		},
		onClosed:function() {
			jQuery(dialogSelector).html(existingHtml);
		}
	});
	jQuery(dialogSelector).empty();
	jQuery("#guideObjectId").val(guideObjectId);

	return false;
}

function showAlertInFancyBox(message){

}

function mapOrderSaveCallBack(data, textStatus){
	if(data=="success"){
		jQuery('#map-order-div-toUpdate').html("<strong>"+msgs["order.map.successful"]+"</strong>");
		jQuery('#submit-button-div').hide();
		jQuery.fancybox.resize();
	}else{
		jQuery('#map-order-div-toUpdate').html(data);
		jQuery.fancybox.resize();
	}
}

function setVisibilityOfMarkers(visible){
	mgr.clearMarkers();
/*
	mgr.processAll_(mgr.shownBounds_, function(marker){
		if(visible){
			marker.show()
		}else{
			marker.hide()
		}
	})
*/
}
