/*
 * initialize/set target marker
 * @param {google.maps.LatLng} targetPos marker position
 ' @param {String} strAddress marker address
 */
function setTargetMarker(targetPos, strAddress) {
	if (targetMarker == undefined) {
		targetMarker = new google.maps.Marker({
			icon: markerImages.targetMarker,
			map: map,
			position: targetPos,
			shadow: markerImages.targetShadow,
			title: strAddress,
			clickable: true,
			zIndex: 9999
		});
		targetMarkerListener = google.maps.event.addListener(targetMarker, 'click', function(){
			displayInfoWindow(targetMarker, '<span class="gminfo">' + strAddress + '</div>');
		});
	} else {
		targetMarker.setPosition(targetPos);
		targetMarker.setTitle(strAddress);
		google.maps.event.removeListener(targetMarkerListener);
		targetMarkerListener = google.maps.event.addListener(targetMarker, 'click', function(){
			displayInfoWindow(targetMarker, '<span class="gminfo">' + strAddress + '</div>');
		});
	};
	displayInfoWindow(targetMarker, '<span class="gminfo">' + strAddress + '</div>');
}

/*
 * format the address data for display in the infowindow
 * @param loc {Object} location
 */
function formatInfoWindowContent(loc) {
	return '<h4>' + loc.name + '</h4>' + 
	'<p>' + 
	loc.address + '<br>' +
	loc.zip + ' ' + loc.city + '<br>' +
	loc.country + '<br><br>' +
	((loc.phone == "") ? "" : loc.phonelabel + loc.phone + '<br>') +
	((loc.fax == "") ? "" : loc.faxlabel + loc.fax + '<br>') +
	((loc.mail == "") ? "" : loc.maillabel + '<a href="mailto:' + loc.mail + '">' + loc.mail + '</a><br>') +
	((loc.website == "") ? "" : loc.websitelabel + '<a href="' + (checkURL(loc.website) ? loc.website : 'http://' + loc.website) + '" target="_blank">' + loc.website + '</a><br>') + 
	('<br><span class="gmnoprint"><a href="../agGetvCard?OpenAgent&amp;id=' + loc.tag + '" target="_blank">' + strDownloadVCardText + '</a></span>') +
	'</p>';
}

/*
 * format the address data for search result output
 * @param loc {Object} location
 */
function formatSearchResultContent(loc) {
	var lbr = "<br>";
	var refLoc = taLocations[loc.tag];
	return('<tr><td class="ls-address"><address>' + 
	'<a href="#" class="ls-companyname" onclick="displayLocation(\'' + loc.tag + '\'); return false;" title="' + strShowAddressText + '">' + refLoc.name + '</a>' + lbr + 
	refLoc.address + lbr + 
	refLoc.zip + " " + refLoc.city + lbr +
	((refLoc.country == "") ? "" : refLoc.country) +
	'</address>' + 
	((refLoc.website == "") ? "" : '<a href="' + (checkURL(refLoc.website) ? refLoc.website : 'http://' + refLoc.website) + '" target="_blank">' + refLoc.website + '</a>') +
	'</td><td class="ls-contact">' +
	('<span class="ls-dist">Entfernung: ' + loc.dist.toString() + " km</span>") +
	((strCenterImageUrl == "") ? "" : '<img src="' + strCenterImageUrl + '" onclick="centerLoc(\'' + loc.tag + '\'); return false;" title="' + strCenterTitle + '" class="centerimg">') +
	lbr + lbr +
	((refLoc.phone == "") ? "" : refLoc.phonelabel + ' ' + refLoc.phone + lbr) + 
	((refLoc.fax == "") ? "" : refLoc.faxlabel + ' ' + refLoc.fax + lbr) + 
	((refLoc.mail == "") ? "" : '<a href="mailto:' + refLoc.mail + '">' + refLoc.mail + '</a>' + lbr) +
	(lbr + '<span class="gmnoprint"><a href="../agGetvCard?OpenAgent&amp;id=' + loc.tag + '" target="_blank">' + strDownloadVCardText + '</a></span>') +
	'</td></tr>');
}

/*
 * Display InfoWindow - make sure only one InfoWindow is displayed at a time
 * @param {google.maps.Marker} marker to attach the InfoWindow to
 * @param {Number} locaionId array index of location the marker represents
 */
function displayInfoWindow(marker, infoContent) {
	if (infoWindow == undefined) {
		infoWindow = new google.maps.InfoWindow({
			content: infoContent
		})
	} else {
		infoWindow.setContent(infoContent)
	}
	infoWindow.open(map, marker);
}

/*
 * display single marker and infowindow - closure function
 * @param taLoc {String} listtag
 */
function displayMarker(taLoc) {
		var taPos = new google.maps.LatLng(taLocations[taLoc].lat, taLocations[taLoc].lng);
		var marker = new google.maps.Marker({
			id: taLoc,
			icon: markerImages.marker,
			map: map,
			position: taPos,
			shadow: markerImages.shadow,
			title: taLocations[taLoc].name.replace(/<br>/, " "),
			clickable: true
		});
		taLocations[taLoc].marker = marker;	// store marker for later reference
		google.maps.event.addListener(marker, 'click', function(){
			displayInfoWindow(marker, '<div class="infowindow">' + formatInfoWindowContent(taLocations[taLoc]) + "</div>");
		});
}

/*
 * display markers on map
 */
function displayMarkers() {
	for (var taLoc in taLocations) { 
		displayMarker(taLoc);
	}
}

/*
 * code address, display dialog to select address on multiple matches
 * @param {String} strAddress address to geocode
 * @return {google.maps.LatLng} target location (null if multiple matches)
 */
function codeAddress(strAddress) {
  if (geocoder) {
  	var loc = dojo.locale;
  	var dashpos = loc.indexOf("-");
	var region = (dashpos > 0) ? loc.substring(0, pos) : loc;
    geocoder.geocode( { 'address': strAddress, 'language': loc, 'region': region}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {	// Geocoder success
	      if (results.length == 1) { // single hit
    	    map.setCenter(results[0].geometry.location);
    	    if (results[0].geometry.bounds == undefined) {
    	    	map.setZoom(8);
    	    } else {
	        	map.fitBounds(results[0].geometry.bounds);
	        	map.setZoom((map.getZoom() > 9) ? 8 : map.getZoom()-2);
	        }
	        setTargetMarker(results[0].geometry.location, results[0].formatted_address);
			locationSearch(results[0].formatted_address, results[0].geometry.location);
	      } else { // multiple hits - display list
	      	var entriesList = "";
	      	var introText = (strSelectLocationIntro == "") ? "" : '<p>' + strSelectLocationIntro + '</p>\n';
	      	var otherEntry = (strOtherLocationText == "") ? "" : '<li><a href="#" onclick="myDialog.hide(); return false;">' + strOtherLocationText + '</a></li>\n';
	      	dojo.forEach(results, function(entry, i) {
	      		entriesList += '<li><a href="#" onclick="codeAddress(\'' + entry.formatted_address + '\'); myDialog.hide(); return false;">' + entry.formatted_address + '</a></li>\n'
	      	});
	      	if (myDialog == undefined) {
		      	myDialog = new dijit.Dialog({
		      		id: "selectLocationDlg",
		      		title: strSelectLocationHeadline,
		      		content: '<div class="dlg">' + introText + '<ul>\n' + entriesList + '\n' + otherEntry + '</ul></div>'
		      	})
	      	} else {
	      		myDialog.attr("title", strSelectLocationHeadline);
	      		myDialog.attr("content", '<div class="dlg">' + introText + '<ul>\n' + entriesList + '\n' + otherEntry + '</ul></div>')
	      	}
	      	myDialog.show();
	      	return null;
	      }
	  } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
			if (myDialog == undefined) {
		      	myDialog = new dijit.Dialog({
		      		id: "selectLocationDlg",
		      		title: strErrHeadlineNoMatch,
		      		content: '<div class="dlg">' + strErrMsgNoMatch.replace(/%%QUERY%%/gi, strAddress) + '</div>'
		      	})
	      	} else {
	      		myDialog.attr("title", strErrHeadlineNoMatch);
	      		myDialog.attr("content", '<div class="dlg">' + strErrMsgNoMatch.replace(/%%QUERY%%/gi, strAddress) + '</div>')
	      	}
	      	myDialog.show();
			return null;
      } else {	// Geocoder returned error
			if (myDialog == undefined) {
		      	myDialog = new dijit.Dialog({
		      		id: "selectLocationDlg",
		      		title: strErrHeadlineGeocoder,
		      		content: '<div class="dlg">' + strErrMsgGeocoder + '</div>'
		      	})
	      	} else {
	      		myDialog.attr("title", strErrHeadlineGeocoder);
	      		myDialog.attr("content", '<div class="dlg">' + strErrMsgGeocoder + '</div>')
	      	}
	      	myDialog.show();
			return null;
      }
    });
  }
}

/*
 * submit the location search form
 */
function submitLocationSearch() {
	if (inputValidation('locationquery')) {
		codeAddress(dojo.byId('locationquery').value);
	}
	return false;
}

/*
 * if the url parameter locationquery is set, this function starts a search after the page has loaded
 */
function onLoadSearch() {
	if (strTargetLocation != "") {
		dojo.byId('locationquery').value = strTargetLocation;
		codeAddress(strTargetLocation);
	}
}

/*
 * start the location search and display the results
 * @param strQuery {String} search query
 * @param targetLatLng {google.maps.LatLng} target position
 */
function locationSearch(strQuery, targetLatLng) {
		dojo.xhrGet({
			url: "../agLocationSearch?Open",
			handleAs: "json",
			timeout: 5000,
			content: {
				'maxresults': intMaxResults, 
				'maxdist': intMaxDist,
				'sourceunid': PageUNID,
				'lat': targetLatLng.lat(),
				'lon': targetLatLng.lng()
			},
			load: function(response, ioArgs) {
				if (response.status="OK") {
					lastQuery = strQuery;
					lastSearchResponse = response; // store search response
					if (strMyGoalUrl != "" && pageTracker != undefined) {
						// Track goal conversion in Google Analytics
						pageTracker._trackPageview(strMyGoalUrl);
					}
					if (trackWA="GA" && pageTracker != undefined) {
						// Track search as event in Google Analytics
						strGAlabel = strQuery;
						strGAvalue = response.results.length;	
						pageTracker._trackEvent(strGAcategory, strGAaction, strGAlabel, strGAvalue);
					};
					trackConversion(); // Track conversion in Google
					displayResults(strQuery, response.results, response.status);
				} else {
					console.log("response has errors", response, iOArgs); // ##
					displayResults(strQuery, response.results, response.status);
				}
				return response;
			},
			error: function(response, ioArgs) {
				console.log("error", response, ioArgs); // ##
				displayResults(strQuery, response.results, response.status);
				return response;
			}
		})
}

/*
 * display search results
 * @param strQuery {String} search query
 * @param results {Array} results array
 * @param status {String} response status
 */
function displayResults(strQuery, results, status) {
	var searchtxt = "";
	var entriestable = "";
	if (status == "OK") {
		if (results.length > 0) {
			resetCurrentMarker();
			searchtxt = '<p>' + strTextResult.replace(/%%QUERY%%/gi, strQuery).replace(/%%HITS%%/, results.length.toString()) + '</p>';
			var entries = dojo.map(results, function(x) {
				return formatSearchResultContent(x);
			});
			entriestable = '<table class="ls-results">' + entries.join(" ") + '</table>';
		} else {
			searchtxt = '<p>' + strTextNoResult.replace(/%%QUERY%%/gi, strQuery).replace(/%%MAXDIST%%/gi, intMaxDist.toString()) + '</p>';
		};
	} else {
		searchtxt = '<p>' + strErrMsgGeocoder + '</p>';
	}
	var resultspane = dojo.byId("location_searchresults");
	resultspane.innerHTML = '<h3>' + strHeadlineResult + '</h3>' + searchtxt + entriestable;
	dojo.addClass(resultspane, "displayresults");
	return false;
}

/*
 * display the last search results again
 */
function displayLastResults() {
	displayResults(lastQuery, lastSearchResponse.results, lastSearchResponse.status);
}

/*
 * Called when a search result entry is clicked:
 * - center on search location
 * - switch marker icon
 * - set bounds to display both target and selected marker
 * @param tag location tag
 */
function centerLoc(tag) {
	loc = taLocations[tag];
	if (curMarker != loc.marker) {
		resetCurrentMarker();
	};
	curMarker = loc.marker;
	curMarkerZindex = curMarker.getZIndex();
	loc.marker.setIcon(markerImages.resultMarker);
	loc.marker.setShadow(markerImages.resultShadow);
	loc.marker.setZIndex(targetMarker.getZIndex() - 1);
	if (loc.marker.getPosition().lng() < targetMarker.getPosition().lng()) {
		map.fitBounds(new google.maps.LatLngBounds(loc.marker.getPosition(), targetMarker.getPosition()));
	} else {
		map.fitBounds(new google.maps.LatLngBounds(targetMarker.getPosition(), loc.marker.getPosition()));
	}
	map.setZoom(map.getZoom() - 2);
	map.setCenter(loc.marker.getPosition());
	displayInfoWindow(loc.marker, '<div class="infowindow">' + formatInfoWindowContent(loc) + "</div>");
}

/*
 * display single location instead of the search results
 */
function displayLocation(tag) {
	centerLoc(tag);
	var resultspane = dojo.byId("location_searchresults");
	resultspane.innerHTML = formatInfoWindowContent(taLocations[tag]) + 
	'<p class="gmnoprint"><a href="#" onclick="displayLastResults(); return false;">' + strShowResultsText + '</a></p>';
	dojo.addClass(resultspane, "displayresults");
	return false;
}

/*
 * reset the icon and z-index of the current result marker
 */
function resetCurrentMarker() {
	if (curMarker != undefined) {
		curMarker.setIcon(markerImages.marker);
		curMarker.setShadow(markerImages.shadow);
		curMarker.setZIndex(curMarkerZindex);
	};
}
	
/* 
 * input validation for the location search form
 * @param {String} strFieldName search query field id
 */
function inputValidation(strFieldName)
{
	var objField = dojo.byId(strFieldName);
	if (objField != undefined)
	{
		var strFieldValue = objField.value;
		if ( (strFieldValue == "") || (strFieldValue == strErrMsgNoQuery) || (strFieldValue == strPresetText) )
		{
			objField.value = strErrMsgNoQuery;
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}	
}

/*
 * functions to check query field value
 */
function connectQueryEvents() {
	var queryNode = dojo.byId("locationquery");
	queryNode.value = strPresetText;
	dojo.connect(
		queryNode,
		"onfocus",
		function () {
			var strValue = queryNode.value;
			if (strValue == strPresetText || strValue == strErrMsgNoQuery) {queryNode.value = ''};
			return true;
		}
	);
	dojo.connect(
		queryNode,
		"onblur",
		function () {
			var strValue = queryNode.value;
			if (strValue == '') {queryNode.value = strPresetText};
			return true;
		}
	);
}

/*
 * checkURL()
 * usage: checks if URL starts with 'http://' or 'https://'
 * @param {string} $raw_url
 * @return {boolean} true = url is correct; false = url is wrong
 */
function checkURL(rawurl) {
	if (rawurl.match(/^(http(s?):\/\/{1})((\w+\.){1,})\w{2,}(\/?)$/i)) {
		return true;
	} else {
		return false;
	}
}

/*
 * load Google conversion code in an iframe when a search has been performed. 
 */
function conversionCallback() {
	return true;
}
function trackConversion() {
	if (gcFrame == undefined) {
		gcFrame = dojo.io.iframe.create("gconversion", "conversionCallback()", "../vwAddBodyEndHTML_Search/" + PageUNID);
	} else {
		reloadIFrame(gcFrame);
	}
}
/*
 * reload the iframe content
 * @param objFrame {dojo.io.iframe}
 */
function reloadIFrame(objFrame) {
	var idoc;
	if(dojo.isIE || dojo.isWebKit > 521){
		idoc = objFrame.contentWindow;
	}else if(dojo.isSafari){
		idoc = objFrame.document;
	}else{
		idoc = objFrame.contentWindow;
	};
	if(!idoc){
		objFrame.location.reload()
	}else{
		idoc.location.reload();
	}
}