var initialValues = { 
	radius: 200000,
	itemsPerPage: 20,
	initialItems: 100,
	absoluteMaxItems: 300,                                           
	openinghoursLabel: "Öffnungszeiten",
	phoneLabel: "Tel.",
	chunkSize: 20,
	mode: "search"
};
function searchPreInitialized(searchUrl, initdata) {
	var cook = document.cookie;
 	
	return initialValues;
}
function merge(data1, data2) {
	var newData = data1;
	for (var key in data2) {
		newData[key] = data2[key];
	}
	return newData;
}
	

function searchPreInitializedSuccess(serverdata, userdata) {
	
	var newData = merge(serverdata, userdata);
	//jQuery.merge(serverdata, userdata);
	
	initStorelocator(newData);
	search_main();
}
function setPrintDlgTexts() {
	if (initialValues["label_print"] != undefined) {
		$('#print-link').html(initialValues["label_print"]);
	}
	if (initialValues["label_back"] != undefined) {
		$('#back-link').html(initialValues["label_back"]);
	}
	if (initialValues["headline"] != undefined) {
		$('#headline_').html(initialValues["headline"]);
	}
}

function initStorelocator(values) {
	for (var key in values) {
		initialValues[key] = values[key];
	}
	var v = initialValues;
	v["putconfig"] = true;	
	$.ajax({ 
		url: initialValues["searchUrl"], 
		data: v, 
		dataType: 'json'
	});
	
	/*
	var cookies = document.cookie.split(';');
	var cook = "storelocator_data=" + escape(JSON.stringify(initialValues));
	//alert(cook);
	document.cookie = cook;
	//alert(document.cookie);
	*/
}
var mainCalled=false;
var coder = new GClientGeocoder();
var map;

$(function() {
	if (!mainCalled)
		search_main();
});

function search_main() {
	// initialize map
	//getInitialValues();
	mainCalled = true;
	$("#storelocatorform").submit(function() {
		return performNewSearch();
	});
	$("#submit-search").click(function() {
		return performNewSearch();
	});
	map = new GMap2($("#map-canvas").get(0));
	var initCenter = new GLatLng(50.75035931136963,10.146972723305225);
	map.setCenter(initCenter, 1);
	//map.enableGoogleBar();
	// set some variables
	var currentMarkerId;
	var currentMarkerIdTemp;
	var routeStatusChanged = false;
	var routeAction = 'start';
	var sidebarVisible = false;
	var sidebarWidth = 280;
	var resSidebarWidth = 280;
	var dirSidebarWidth = 350;
	var mapHeight = 417;
	var toaddr = '';
	var fromaddr = '';
	var directionsPanel;
	var gdir;
	var currentPage = 0;
	var currentPage = 0;
	var marker = [];
	var resultData = [];
	var shops = [];
	var searchResults = [];
	var indexTriumph = 0;
	var indexOther = 0;
	var indexTotal = 0;
	var searchMode = "none";
	var zoomListener;
	var moveListener;
	var userWantsSidebar = true;
	var requestID;
	var searchReadyCallback = undefined;
	var chunkSize = 20;
	var mapPanned = false;
	var locale = $("input[name=locale]").val();
	var lastSearchData = { }; //backup for print!	
	// set map controls
	var mapControl = new GLargeMapControl();
	map.addControl(mapControl, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15,15) ) );
	
	// set base icon
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.iconSize = new GSize(18, 41);
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.iconAnchor = new GPoint(9, 41);
	baseIcon.imageMap = new Array(0, 0, 18,0, 18,41, 0,41);
	baseIcon.infoWindowAnchor = new GPoint(9, 31);
	
	// set 4 markers to the map at random locations
	var markers = [];
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();	
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	
	initCampaignFilter();
	enablePrintButton();
	var sessionIDExp = /JSESSIONID=([^;]+)/;
	result = sessionIDExp.exec(document.cookie);
	initialValues["sessionid"] = RegExp.$1;	
	// prepare directions
	//initDirections();
	
	// bind click events in info window
	//rebindRouteLinks();
	
	//initMarkers();
	
	
	//initPaging()	
	// resize sidebar if necessary
	//resizeSidebar( sidebarWidth );
	
	// show/hide result list
	if (initialValues["mode"] == "print") {
		userWantsSidebar = false;
		search4Print();
	}
	else {
		showCountryMap(locale);
		$('#show-hide-btn > a').click( function(e) {
			e.preventDefault();
			$(this).blur();
			showHideSidebar(!sidebarVisible);
			userWantsSidebar = sidebarVisible;
		});
		$('#goto-previous-page > a').click(function() {
				if (currentPage > 0) {
					gotoPage(currentPage-1);
				}
		});
		$('#goto-next-page > a').click(function() {
				gotoPage(currentPage+1);
				/*
				pageCount = Math.floor((shops.length-1) / initialValues["itemsPerPage"]);
				if (currentPage < pageCount) {
				}
				*/
		});
		/* initially hide print button?
		$('#print-button').css('color', '#58534B').css('visibility', 'hidden').unbind('click').bind('click', function() { return false; });
		*/
	}
	/* opens the print dialog */
		
	function showCountryMap(address) {
			lastSearchData = {
					method: "post",
					addr: address, 
					checkhomewear: $("#checkhomewear:checked").val(),
					checkleisurewear: $("#checkleisurewear:checked").val(),
					checklingerie: $("#checklingerie:checked").val(),
					checkactions: $("#checkactions:checked").val(),
					country: $("input[name=country]").val(),
					locale: $("input[name=locale]").val(),
					brand: initialValues["brand"],
					radius: initialValues["radius"],
					amount: 20,
					from: 0,
					to: 20,
					requestID: 12
				}; 
			maxItems = initialValues["initialItems"];
			$.ajax({ 
				url: initialValues["searchUrl"], 
				data: lastSearchData,
				cache: false,
				success: function(data, status, xmlhhtp) { onShowCountryMap(data); },
				error: function() {  },
				dataType: 'json'
			});
			return false;
		coder.getLatLng(address, onShowCountryMap);
	}
	function onShowCountryMap(data) {
		/* get bounds from google advice */
		swBounds = new GLatLng(Number(data["south"]), Number(data["west"]));
		neBounds = new GLatLng(Number(data["north"]), Number(data["east"]));
		mapBounds = new GLatLngBounds(swBounds, neBounds);
		zoomlevel = map.getBoundsZoomLevel(mapBounds);
		center = new GLatLng(Number(data["lat"]), Number(data["lon"]));
		map.setZoom(zoomlevel);
		map.panTo(center);
	}

	function showPrint() {
		var hoehe = 730;
		var breite = 700;
		var links = (screen.width/2)-(breite/2);
		var oben = (screen.height/2)-(hoehe/2);
		
		var data = merge(initialValues, lastSearchData);
		data["page"] = currentPage;
		var bounds = map.getBounds();
		var failCoords = { 
				faileast: bounds.getNorthEast().lng(),
				failnorth: bounds.getNorthEast().lat(),
				failwest: bounds.getSouthWest().lng(),
				failsouth: bounds.getSouthWest().lat(),
				faillat: map.getCenter().lat(),
				faillon: map.getCenter().lng(),
				failzoom: map.getZoom()
		};
		data = merge(data, failCoords);

		query = encodeURIComponent($.toJSON(data));
		var popup_url = "/storelocator/popup_print.jsp";

		var printwin = window.open(popup_url + 
			"?query=" + query,"triumph","height="+hoehe+",width=" + breite + ",status = no,toolbar = no,menubar = no,location = no,resizable = no,titlebar = yes,scrollbars = yes,fullscreen = no,top ="+oben+",left ="+links);
	}
	
	function hideMsgs() {
		$('#search-error').fadeOut();
		$('#result-pager').css('visibility', 'hidden');
	}
	function initCampaignFilter() {
		if (initialValues["mode"] != "print") {
			$.ajax({ 
				url: initialValues["searchUrl"],
				cache: false,
				data: { 
					getcampaign: true,
					locale: locale,
					country: locale,
					brand: initialValues["brand"]
				}, 
				success: function(data, status, xmlhhtp) { gotCampaignFilter(data); },
				error: function() { showErrorMsg(); },
				dataType: 'json'
			});
		}
	}
	function gotCampaignFilter(data) {
		if (data["campaign"]) {
			$('#searchactions').css('display', 'block');
		} else {
			$('#searchactions').css('display', 'none');
			$('input[name=checkactions]').attr('checked', 'false');
		}
	}
	/* inits common search props */ 
	function initSearch() {
		//disable button while search in progress
		disablePrintButton();
		
		initialValues["chunkSize"] = 20;
		currentChunk = 0;
		currentPage = 0;
		indexTriumph = 0;
		indexOther = 0;
		indexTotal = 0;
		numPages = 0;
		map.clearOverlays();
		shops = [];
		marker = [];
		searchResults = [];
		redraw({sidebar: true, markers: true});
		
		chunkSize = initialValues["chunkSize"];
		//userWantsSidebar = true;
		window.clearTimeout();
		$('#goto-previous-page').css('visibility', 'hidden');
		hideMsgs();
	}
	
	function performNewSearch() {
		initSearch();	
		ret = searchByAddress();
		$('#checkactions').click(productChecked);
		$('#checkhomewear').click(productChecked);
		$('#checkleisurewear').click(productChecked);
		$('#checklingerie').click(productChecked);
		$('#checkbrand1').click(productChecked);
		$('#checkbrand2').click(productChecked);
		$('#checkbrand3').click(productChecked);
		$('#checkbrand4').click(productChecked);
		$('#checkbrand5').click(productChecked);
		$('#checkbrand6').click(productChecked);
		$('#shops-near').css('display','none');
		mapPanned = false;
		return ret;
	}
	/*
	get the initial values from the backend 
	*/
	function getInitialValues() {
		//alert("getting values!");
		$.ajax({ 
			url: initialValues["searchUrl"], 
			data: { 
				initvalues: true 
			}, 
			error: function() { showErrorMsg(); },
			async: false,
			cache: false,
			dataType: 'json'
		});
		return false;
	}
	function searchByAddress() {
		removeStandardListeners();
		searchMode = "address";
		initialValues["searchmode"] = "address";
		searchText = $("input[name='addr']").val();
		requestID = new Date();
		brands= initialValues["brand"];
		if(document.getElementById("checkbrand1")){		//checkbrand-fields exist? Either all of them or none
			if (document.getElementById("checkbrand1").checked
				|| document.getElementById("checkbrand2").checked
				|| document.getElementById("checkbrand3").checked
				|| document.getElementById("checkbrand4").checked
				|| document.getElementById("checkbrand5").checked
				|| document.getElementById("checkbrand6").checked){
				brands = "";
				for (var i=0; i<brandsfilter.length; i++){
	                if (document.getElementById("checkbrand"+(i+1)).checked){
	                    if (brands.length>0) {
	                        brands += ",";
	                    }
	                    brands += brandsfilter[i];
	                }
	            }
	        }
		} 
		//console.log('brandfilter:' + brands);
		//console.log('getting stores %d to %d for address %s', currentChunk * initialValues["itemsPerPage"], (currentChunk + 1) * initialValues["itemsPerPage"], searchText);
		lastSearchData = {
				method: "post",
				addr: encodeURIComponent(searchText), 
				checkhomewear: $("#checkhomewear:checked").val(),
				checkleisurewear: $("#checkleisurewear:checked").val(),
				checklingerie: $("#checklingerie:checked").val(),
				checkactions: $("#checkactions:checked").val(),
				country: $("input[name=country]").val(),
				locale: locale,
				brand: brands,
				radius: initialValues["radius"],
				amount: initialValues["absoluteMaxItems"],
				from: currentChunk * chunkSize,
				to: (currentChunk + 1) * chunkSize,
				currentRequestID: requestID.getTime()
			}; 
		maxItems = initialValues["initialItems"];
		$.ajax({ 
			url: initialValues["searchUrl"], 
			data: lastSearchData,
			cache: false,
			success: function(data, status, xmlhhtp) { showResults(data); },
			error: function() { showErrorMsg(); },
			dataType: 'json'
		});
		return false;
	}
	
	function searchByMapBounds() {
		removeStandardListeners();
		var bounds = map.getBounds();
		searchMode = "bounds";
		initialValues["searchmode"] = searchMode;
		//console.log('getting stores %d to %d for bounds %s', currentChunk * initialValues["itemsPerPage"], (currentChunk + 1) * initialValues["itemsPerPage"], bounds);
		requestID = new Date();
		brands= initialValues["brand"];
		if(document.getElementById("checkbrand1")){		//checkbrand-fields exist? Either all of them or none
			if (document.getElementById("checkbrand1").checked
				|| document.getElementById("checkbrand2").checked
				|| document.getElementById("checkbrand3").checked
				|| document.getElementById("checkbrand4").checked
				|| document.getElementById("checkbrand5").checked
				|| document.getElementById("checkbrand6").checked){
				brands = "";
				for (var i=0; i<brandsfilter.length; i++){
	                if (document.getElementById("checkbrand"+(i+1)).checked){
	                    if (brands.length>0) {
	                        brands += ",";
	                    }
	                    brands += brandsfilter[i];
	                }
	            }
	        }
		} 
		//console.log('brandfilter:' + brands);
		lastSearchData = {
				east: bounds.getNorthEast().lng(),
				north: bounds.getNorthEast().lat(),
				west: bounds.getSouthWest().lng(),
				south: bounds.getSouthWest().lat(),
				checkhomewear: $("#checkhomewear:checked").val(),
				checkleisurewear: $("#checkleisurewear:checked").val(),
				checklingerie: $("#checklingerie:checked").val(),
				checkactions: $("#checkactions:checked").val(),
				country: $("input[name=country]").val(),
				locale: locale,
				brand: brands,
				radius: initialValues["radius"],
				amount: initialValues["absoluteMaxItems"],
				from: currentChunk * chunkSize,
				to: (currentChunk + 1) * chunkSize,
				currentRequestID: requestID.getTime()
			}; 
		maxItems = initialValues["absoluteMaxItems"];
		$.ajax({ 
				url: initialValues["searchUrl"], 
			data: lastSearchData,
			cache: false,
			success: function(data, status, xmlhhtp) { showResults(data); },
			error: function() { showErrorMsg(); },
			dataType: 'json'
		});
		return false;
	}
	
	function search4Print() {
		initSearch();
		requestID = new Date();
		var data = merge(initialValues, { 
				east: initialValues["faileast"],
				north: initialValues["failnorth"],
				west: initialValues["failwest"],
				south: initialValues["failsouth"],
				from: initialValues["page"] * initialValues["itemsPerPage"],
				to: (initialValues["page"]+1) * initialValues["itemsPerPage"],
				/*uselastrequestparams: true,*/
				currentRequestID: requestID.getTime()
			});
		data["putconfig"] = undefined;
		$.ajax({ 
			url: initialValues["searchUrl"], 
			data: data,
			success: function(data, status, xmlhhtp) { showPrintResults(data); },
			error: function() { /*showPrintOnError();*/ showPrintResults(data); },
			dataType: 'json'
		});
		return false;
	}
	
	/* called whenever an ajax result comes in for standard searches */
	function showResults(data) {
		if (data["currentRequestID"] != requestID.getTime())
			return;
		if (userWantsSidebar && !sidebarVisible) {
			showSidebar();
		}
		resultData = data;
		shops = shops.concat(data["resultset"]);
		/* get bounds from google advice */
		if (currentChunk == 0) {
			swBounds = new GLatLng(Number(data["south"]), Number(data["west"]));
			neBounds = new GLatLng(Number(data["north"]), Number(data["east"]));
			mapBounds = new GLatLngBounds(swBounds, neBounds);
			zoomlevel = map.getBoundsZoomLevel(mapBounds);
			center = new GLatLng(Number(data["lat"]), Number(data["lon"]));
			map.setZoom(zoomlevel);
			map.panTo(center);
			if (searchMode == "address") {
				locale = resultData["locale"];
				window.setTimeout(function () { gotCampaignFilter(data); }, 50);
			}
			
		} 
		
		/* is there data for the sidebar */
		if (data["to"] > data["from"])
			window.setTimeout(function() { fillSidebar(data["from"],data["to"]); }, 50);

		currentChunk++;
		if ((shops.length < maxItems) && (shops.length < data["count"])) {
			window.setTimeout((searchMode == "address") ? searchByAddress : searchByMapBounds, 100);
		} else {
			window.setTimeout(addStandardListeners, 500);
			if (shops.length < 1) {
				if (searchMode == "address") {
					hideMsgs();
					$('#shops-near').css('display','none');

					$('#search-error').html(initialValues["radiusErrorLabel"]).fadeIn();
				}
				if (searchMode == "bounds") {
					hideMsgs();
					$('#shops-near').css('display','none');
					$('#search-error').html(initialValues["boundsErrorLabel"]).fadeIn();
					//hides button if no hits
					/*
					if (initialValues["mode"] != "print") {
						$('#print-button').css('color', '#58534B').css('visibility', 'hidden').unbind('click').bind('click', function() { return false; });
					}
					*/
				}
				/* show print button on end of search, even if there's an error */
				enablePrintButton();
			} else {
				$('#search-error').css('display', 'none');
				/*if (searchMode == "address")
					recalcMapCenter();*/
				enablePrintButton();
			}
			
			if (searchReadyCallback != undefined) {
				searchReadyCallback();
				searchReadyCallback = undefined;
			}
			//searchMode = "none";
		}
	}
	function enablePrintButton() 
	{
		if (initialValues["mode"] != "print") {
			$('#print-button').css('color', '#DB001A').unbind('click').bind('click', function() { showPrint(); return false; });
		}
	}
	
	function disablePrintButton() 
	{
		if (initialValues["mode"] != "print") {
			$('#print-button').css('visibility', 'visible').css('color', '#58534B').unbind('click').bind('click', function() { return false; });
		}
	}
	
	function showPrintOnError(data)
	{
		$.ajax({ 
			url: initialValues["searchUrl"],
			cache: false,
			data: { 
				getsavedbounds: true
			},
			success: function(data) { showPrintResults(data, true); },
			error: function() { 
					window.setTimeout(function() {
							window.status="error getting saved coordinates!";
					}, 10000); },
			dataType: 'json'
		});
	}
	function showPrintResults(data, recurse) {
		resultData = data;
		/*
		if (!recurse && ((data == undefined) || (data["resultset"] == undefined) || (data["resultset"].length == 0) || isNaN(data["south"]))) {
			showPrintOnError();
			return;
		} 
		*/
		//alert("ja nun..." + shops.length);
		/* get bounds from google advice */
		shops = data["resultset"];
		if ((currentChunk == 0) && (shops != undefined) && (shops.length > 0)) {
			if (searchMode == "address")
				locale = resultData["locale"];
			
		} 
		/* */
		if ((shops != undefined) && (shops.length > 0)) {
			window.setTimeout(function() {
					var bounds = fillSidebar(0, shops.length);
					/*
					swBounds = new GLatLng(Number(data["failsouth"]), Number(data["failwest"]));
					neBounds = new GLatLng(Number(data["failnorth"]), Number(data["faileast"]));
					mapBounds = new GLatLngBounds(swBounds, neBounds);
					zoomlevel = map.getBoundsZoomLevel(mapBounds);
					center = new GLatLng(Number(data["faillat"]), Number(data["faillon"]));
					map.setZoom(zoomlevel);
					map.panTo(center);
					
					var zoom = map.getBoundsZoomLevel(bounds);
					map.setCenter(bounds.getCenter(), zoom);
					*/
					
			}, 500);
		}
		/*else {*/
			window.setTimeout(function() {
				swBounds = new GLatLng(Number(initialValues["failsouth"]), Number(initialValues["failwest"]));
				neBounds = new GLatLng(Number(initialValues["failnorth"]), Number(initialValues["faileast"]));
				mapBounds = new GLatLngBounds(swBounds, neBounds);
				zoomlevel = map.getBoundsZoomLevel(mapBounds);
				center = new GLatLng(Number(initialValues["faillat"]), Number(initialValues["faillon"]));
				map.setCenter(center, initialValues["failzoom"]);
			}, 50);
		/*}*/
	}
	function showSidebar() {
		showHideSidebar(true);
	}
	function hideSidebar() {
		showSidebar(false);
	}
	function showErrorMsg() {
		if (initialValues["mode"] != "print")
			showSidebar();
		$('#shops-near').css('display','none');

		//hideMsgs();
		$('#search-error').html(initialValues["addressErrorLabel"]).fadeIn();
		
		enablePrintButton();

	}
	function addStandardListeners() {
		removeStandardListeners();
		
		if (moveListener == undefined)
			moveListener = GEvent.addListener(map, "dragend", mapPan);
		if (zoomListener == undefined)
			zoomListener = GEvent.addListener(map, "zoomend", mapZoom);
	}
	function removeStandardListeners() {
		if (zoomListener != undefined) {
			GEvent.removeListener(zoomListener);
			zoomListener = undefined;
		}
		if (moveListener != undefined) {
			GEvent.removeListener(moveListener);
			moveListener = undefined;
		}
		GEvent.clearInstanceListeners(map);
	}
	
	function productChecked() {
		initSearch();
		removeStandardListeners();
		if (searchMode == "address") {
			searchByAddress();
		}
		else {
			searchByMapBounds();
		}
	}
	
	function mapZoom() {
		initSearch();
		
		removeStandardListeners();
		maxItems = initialValues["absoluteMaxItems"];
		//searchReadyCallback = function() { window.setTimeout(showNearMsg, 100); };
		searchByMapBounds();
	}
	function mapPan() {
		mapPanned = true;
		mapZoom();
		//console.log("doing map pan!");
	}
	
	function showNearMsg() {
		if ((shops.length > 0) && (mapPanned)) {
			shopsNear = shops[0]["city"];
			$('#shops-near').html("Shops im Umkreis von " + shopsNear).fadeIn();
		}
		searchReadyCallback = undefined;
	}
	
	function fillSidebar(start, end) {
		//console.log("fill sidebar from %d to %d, currentPage is %d", start, end, currentPage);
		end = Math.min(end, shops.length);
		start = Math.min(start, shops.length);
		if (end > start) {
			$('#result-pager').css('visibility', 'visible');
		}
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		indexTriumph = 0;
		indexOther = 0;
		for (index = start; index < end; index++) {
			treffer = shops[index];
			var icon = new GIcon(baseIcon);
			icon.shadow = "";
			icon.shadowSize = new GSize(0,0);

			var markerOptions = { };
			if ((index > (currentPage*initialValues["itemsPerPage"])-1) && (index < (currentPage+1)*initialValues["itemsPerPage"])) {
				if (treffer["priority"] == "1") {
					imgSrc = "/storelocator/img/crownmarker_" + (indexOther+1)+".png";
					icon.iconSize=new GSize(26,60);
					icon.imageMap = [7,24,1,33,2,41,8,48,10,57,16,57,17,48,24,40,24,31,18,25,22,7,21,3,12,1,3,4,7,18,7,20 ]; 
					indexOther++;
					indexTriumph++;
				}
				else {
					imgSrc = "/storelocator/img/marker_" + (indexOther+1)+".png";
					icon.iconSize=new GSize(24,36);
					indexOther++;
				}
			}
			else {
				imgSrc = "/storelocator/img/dot.png";
				icon.iconSize=new GSize(10,10);
			}
			createSidebarEntry(treffer, imgSrc, currentPage, index);
			pageIndex = Math.floor(index / initialValues["itemsPerPage"]);
			linkCount = $("#pagelinks").children().length;
			if (linkCount < (pageIndex+1)) {
				$("#pagelinks").append("<a class='no-deco' href=''>" + (pageIndex+1) + "</a> ");
				$("#pagelinks a:last-child").click(
					function() {
						gotoPage($("#pagelinks").children().index($(this)));
						
						return false;
					}
				);
				$('#pagelinks > a:eq(' + currentPage + ')').removeClass('no-deco');
				$('#goto-next-page').css('visibility', (pageIndex > 0) ? 'visible' : 'hidden');
			}
			
			icon.image = imgSrc;
			icon.printImage = imgSrc;
			markerOptions["icon"] = icon;
			markerOptions["zIndexProcess"] = function(m) {
				i = m["index"];
				n = currentPage*initialValues["itemsPerPage"];
				if (i < n)
					i += n+initialValues["absoluteMaxItems"]; 
				else {
					if (i+1 > n + initialValues["itemsPerPage"])
						i += initialValues["absoluteMaxItems"];
				}
				return -i; 
			};
			
			var latlng = new GLatLng(treffer["latitude"], treffer["longitude"]);
			m = new GMarker(latlng, markerOptions);
			m["index"] = index;
			marker[index] = m;
			
			indexTotal++;
		}
		
		var bounds = addMarkers(start, end);
		if ((currentChunk == 1) && (searchMode == "address")) {
			var zoom = map.getBoundsZoomLevel(bounds);
			map.setCenter(bounds.getCenter(), zoom);
		}
		return bounds;
	}
	
	function gotoPage(index) {
		start = currentPage * initialValues["itemsPerPage"];
		end = start + initialValues["itemsPerPage"];
		end = Math.min(end, shops.length);
		pageCount = Math.floor((shops.length-1) / initialValues["itemsPerPage"]);
		if (index > pageCount) {
			if ((index * initialValues["itemsPerPage"]) < resultData["count"]) {
				maxItems += initialValues["itemsPerPage"];
				chunkSize = initialValues["itemsPerPage"];
				searchReadyCallback = function () { window.setTimeout(function() { gotoPage(index); }, 500)};
				searchByAddress();
			}
			return;
		}
		removeStandardListeners();
		if ((index != currentPage) && (pageCount > 0)) {
			if (index > 0) {
				$('#goto-previous-page').css('visibility', 'visible');
			}
			
			if (index < pageCount) {
				$('#goto-next-page').css('visibility', 'visible');
			}
			if (index == 0) {
				$('#goto-previous-page').css('visibility', 'hidden');
			}
			/*
			if (index == pageCount) {
				$('#goto-next-page').css('visibility', 'hidden');
			}
			*/
		}
		for (markerindex = start; markerindex < end; markerindex++) {
			map.removeOverlay(marker[markerindex]);
		}
		currentPage = index;

		fillSidebar(start, end);			
		//addMarkers(start, end);

		start = index * initialValues["itemsPerPage"];
		end = start + initialValues["itemsPerPage"];
		end = Math.min(end, shops.length);
		var bounds = fillSidebar(start, end);			
		var zoom = map.getBoundsZoomLevel(bounds);
		map.setCenter(bounds.getCenter(), zoom);

		$('#pagelinks > a').addClass('no-deco');
		$('#pagelinks > a:eq('+index+')').removeClass('no-deco');
			
		//redraw({sidebar: true, markers: true});
		//zoom = zoom - 1;
		/* setting map controls and center*/
		GEvent.addListener(map, "moveend", function() { window.setTimeout(addStandardListeners, 100); });

		window.setTimeout(addStandardListeners, 1000);
	}
	
	function addMarkers(start, end) {
		var latlngbounds = new GLatLngBounds( );
		end = Math.min(end, shops.length);
		var center = map.getCenter();
		cLat = resultData["lat"];
		cLng = resultData["lon"];
		 
		
		for (markerIndex = start; markerIndex < end; markerIndex++) {
			mark = marker[markerIndex];
			mark["index"] = markerIndex;
			map.addOverlay(mark);
			var point = mark.getLatLng();
			if (searchMode == "address") {
				deltaLat = point.lat() - cLat;
				deltaLng = point.lng() - cLng;
				g1 = new GLatLng((cLat + deltaLat), (cLng + deltaLng), true);
				g2 = new GLatLng((cLat - deltaLat), (cLng + deltaLng), true);
				g3 = new GLatLng((cLat - deltaLat), (cLng - deltaLng), true);
				g4 = new GLatLng((cLat + deltaLat), (cLng - deltaLng), true);
				latlngbounds.extend(g1);
				latlngbounds.extend(g2);
				latlngbounds.extend(g3);
				latlngbounds.extend(g4);
			} else
				latlngbounds.extend(point);
			
			if (initialValues["mode"] != "print") {
				$('.search-result:eq('+markerIndex+')').click(function() {
					var i = $('.search-result').index($(this));
					var mark = marker[i];
					map.closeInfoWindow();
					if( i == currentMarkerId ) {
						displayPointNoMove(mark, i);
						
					} else {
						displayPoint(mark, i);
						routeAction = 'start';
						
					}
				});
				GEvent.addListener(mark, "click", function() {
					//var i = $('.search-list').index(this);
					currentIndex = this["index"];
					map.closeInfoWindow();
					if( currentIndex == currentMarkerId ) {
						displayPointNoMove(this, currentIndex);
					} else {
						displayPoint(this, currentIndex);
						routeAction = 'start';
					}
				});
				GEvent.addListener(mark, "infowindowclose", function(){
					currentIndex = this["index"];
					//var i = $('.search-list').index(this);
					if( routeStatusChanged == true && currentIndex == currentMarkerId ) {
						displayPointNoMove(mark, currentIndex);
						routeStatusChanged = false;
						routeAction = 'start';
					}
					currentMarkerId = null; //bjurkowski
				});
			}
		}
		return latlngbounds;
	}
	
	function createSidebarEntry(treffer, imgSrc, page, index) {
		
		if (index > searchResults.length-1) {
			div = document.createElement("div");
			$('#dyn-result').append(div);
			
			var imgdiv = document.createElement("div");
			div.appendChild(imgdiv);
			$(div).addClass("search-result");
			$(imgdiv).addClass("search-image");
			imgdiv.setAttribute("id", "img-"+index);
			var img=document.createElement("img");
			imgdiv.appendChild(img);
			$(img).addClass("search-img");
			
			var textdiv = document.createElement("div");
			div.appendChild(textdiv);
			$(textdiv).addClass("search-text");
			var inner = "";
			inner += "<h4>" + treffer["name"] + "</h4>";
			inner += "<p><span class='address-to'>" + treffer["street"] + "<br />";
			inner += treffer["zip"] + " " + treffer["city"] + "<br /></span>";
			if (treffer["phone"] != "")
				inner += initialValues["phoneLabel"] + " " + treffer["phone"] + "<br />";
			if (treffer["fax"] != "")
				inner += initialValues["faxLabel"] +" " + treffer["fax"] + "<br />";
			if (treffer["home"] != "")
				//inner += initialValues["homepageLabel"] +" " + treffer["home"] + "<br />";
				inner += treffer["home"] + "<br />";
			inner += "</p>";
			
			if (treffer["openinghours"] != "") {
				inner += "<p>" + initialValues["openinghoursLabel"]+":<br />";
				inner += treffer["openinghours"];
				inner += "</p>";
			}
			if ((treffer["checkhomewear"]!="")||(treffer["checkleisurewear"]!="")||(treffer["checklingerie"]!="")) {
				inner +="<p>" + initialValues["productgroupLabel"] + "<br /><span class='productgroups'>";
				if (treffer["checkhomewear"]!="")
				inner += initialValues["hwLabel"] + ", ";
				if (treffer["checkleisurewear"]!="")
					inner += initialValues["lwLabel"] + ", ";
				if (treffer["checklingerie"]!="")
					inner += initialValues["iaLabel"] + ", ";
				inner = inner.substring(0, inner.length-2);
				inner += "</span></p>";
			}
			textdiv.innerHTML = inner;
			
			searchResults[index] = div;
			if ((initialValues["mode"] == "print") && (index % 2 == 1)) {
				$('#dyn-result').append('<br clear="all" />');
			}
		
		}
		div = searchResults[index];
		$('#img-'+index +' > img').attr("src", imgSrc);
		
		if ((index < (page*initialValues["itemsPerPage"])) || (index > (page+1)*initialValues["itemsPerPage"]-1))
			$(div).addClass("invisible");
		else
			$(div).removeClass("invisible");
	}

	function initDirections() {
		directionsPanel = document.getElementById("directions-list");
		gdir = new GDirections(map, directionsPanel);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
		GEvent.addListener(gdir, "error", handleErrors);
	}
	
	//function setDirections(fromAddress, toAddress, locale) {
	function setDirections( caller ) {
		fromaddr = $(caller).parent().parent().parent().parent().find('#fromaddr').val();
		toaddr = $('#toaddr').val();
		$('#result-list').css('display', 'none');
		$('#result-pager').css('display', 'none');
		$('#directions-list').css('display', 'block');
		map.clearOverlays();
		map.closeInfoWindow();
		gdir.load("from: " + fromaddr + " to: " + toaddr);
	}
	
	function onGDirectionsAddOverlay(){ 
		resizeSidebar( dirSidebarWidth );
		if( sidebarVisible === true ) {
			map.panBy( new GSize((dirSidebarWidth/2), 0 ) );
		}
		var latLngs;
		var targetIcon = new GIcon(G_DEFAULT_ICON);
		targetIcon.iconSize = new GSize(24, 32);
		targetIcon.shadowSize = new GSize(0, 0);
		targetIcon.iconAnchor = new GPoint(12, 21);
		targetIcon.imageMap = new Array(0, 0, 24,0, 24,32, 0,32);
		targetIcon.image = "/storelocator/img/marker_target.png";

		var originalMarker = gdir.getMarker(1);
		latLngs = originalMarker.getLatLng();
		map.removeOverlay(originalMarker);
		newMarker = new GMarker(latLngs,{icon:targetIcon});
		map.addOverlay(newMarker);
		
	}

	function displayPoint(mark, index) {
		removeStandardListeners();
		var moveEnd = GEvent.addListener(map, "moveend", function(){
			index = mark["index"];
			//mark = marker[index];
			mark.openInfoWindow(createMarkerHtml(index));
			//rebindRouteLinks();
			currentMarkerId = index;
			GEvent.removeListener(moveEnd);
			window.setTimeout(addStandardListeners, 200);
		});
		currentMarkerId = index;
		if( sidebarVisible == false ) {
			map.panTo( calculateCenter(mark, mapHeight, 0 ) );
		} else {
			map.panTo( calculateCenter(mark, mapHeight, sidebarWidth ) );
		}
	}
	
	function displayPointNoMove(mark, index) {
		removeStandardListeners();
		index = mark["index"];
		//mark = marker[index];
		mark.openInfoWindow( createMarkerHtml(index));
		rebindRouteLinks();
		currentMarkerId = index;
		
		window.setTimeout(addStandardListeners, 200);
	}
	
	function rebindRouteLinks() {
		$('.route-to').bind('click', function(e){
			e.preventDefault();
			routeStatusChanged = true;
			routeAction = 'to';
			map.closeInfoWindow();
			$('#route-view-2 #toaddr').val( toaddr );
		});
		$('.route-from').bind('click', function(e){
			e.preventDefault();
			routeStatusChanged = true;
			routeAction = 'from';
			map.closeInfoWindow();
		});
		$('.route-start').bind('click', function(e){
			e.preventDefault();
			routeStatusChanged = true;
			routeAction = 'start';
			map.closeInfoWindow();
		});
		$('.gobtn').bind('click', function(e) {
			e.preventDefault();
			setDirections(this);
		});
	}
	

	
	function createMarkerHtml(index) {
		var route;
		route = $('#route-planner');
		$('#route-planner > div').css('display', 'none');
		switch( routeAction ) {
			case 'to':
			$('#route-view-2').css('display', 'block');
			break;
			case 'from':
			$('#route-view-3').css('display', 'block');
			break;
			case 'start':
			$('#route-view-1').css('display', 'block');
			break;
			default:
			$('#route-view-1').css('display', 'block');
			break;
		}
		var html = $('#info-window')
					.empty()
					.append( $('#dyn-result .search-result:eq('+index+') > .search-text').html() )
					.append( '<div class="route-planner">' )
					.append( route )
					.append( '</div>' )
					//.append( $('#route-wrapper .route-view-2').html() )
					.wrapInner( '<div class="marker-content"></div>' );
		//route.show();
		toaddr = $('#dyn-result .search-result:eq('+index+') > .search-text .address-to').text();
		//fromaddr = $('#dyn-result .search-result:eq('+index+') > .search-text .address-to').text();
		return html.html();
	}
	
	function calculateCenter( marker, mapHeight, mapWidth ) {
		var x = Math.abs(mapWidth/2)-70;
		var y = Math.abs(mapHeight/3);
		var tmpPoint = map.fromLatLngToContainerPixel( marker.getLatLng() );
		tmpPoint = new GPoint( (tmpPoint.x - x), (tmpPoint.y - y) );
		//tmpPoint = new GPoint( (tmpPoint.x - x), tmpPoint.y );
		return map.fromContainerPixelToLatLng( tmpPoint );
	}
	
	function resizeSidebar( newSidebarWidth ) {
		sidebarWidth = newSidebarWidth;
		if( sidebarVisible === false ) {
			if( parseInt( $('#result-container').css('width') ) != sidebarWidth ) {
				$('#result-container').css({'width':sidebarWidth+'px', 'left':'-'+sidebarWidth+'px'});
				$('#show-hide-btn').css( {'left':'-1', 'border-left':'1px solid #fff'} );
				return true;
			}
		} else {
			if( parseInt( $('#result-container').css('width') ) != sidebarWidth ) {
				$('#result-container').animate({'width':sidebarWidth+'px'});
				$('#show-hide-btn').animate( {'left':(sidebarWidth-1)+'px'} );
				return true;
			}
		}
	}
	
	function showHideSidebar(show) {
		//bjurkowski
		if(currentMarkerId != null)
			currentMarkerIdTemp = currentMarkerId;		
		if(show) {
			if (sidebarVisible == false) {
				sidebarVisible = true;			
				$('#show-hide-btn').find('img').attr('src', '/storelocator/img/btn_result_hide.png').end().
					animate({'left':(sidebarWidth-1)+'px'}).css({'border-left':'1px solid #fff'});
				$('#result-container').animate( {'left':'0'}, '', '', function() {
						$('#result-list').css({'overflow':'auto'});
						$('#directions-list').css({'overflow':'auto'});
						$('#logocontrol').css('left', parseInt( $('#logocontrol').css('left') ) + sidebarWidth + 'px');
				});
				$("#map-canvas").css('width', '460px');
				$("#map-canvas").css('left', '280px');
				map.checkResize();
				map.panBy(new GSize(-140, 0));
				//redraw({markers: true});
			}
		} else {
			if (!show) {			
				sidebarVisible = false;
				$('#show-hide-btn').find('img').attr('src', '/storelocator/img/btn_result_show.png').end().animate( {'left':'-1px'} ).css({'border-left':'1px solid #eee'});
				$('#result-list').css({'overflow':'hidden'});
				$('#directions-list').css({'overflow':'hidden'});
				$('#result-container').animate( {'left':'-'+(sidebarWidth-1)+'px'}, '', '', function() {
				$('#logocontrol').css('left', parseInt( $('#logocontrol').css('left') ) - sidebarWidth + 'px');
				});
				$("#map-canvas").css('width', '740px');
				$("#map-canvas").css('left', '0px');
				map.checkResize();
				map.panBy(new GSize(140, 0));
				//redraw({markers: true});
			}
		}
	
		return false;
	}
	function redraw(options) {
		indexTriumph = 0;
		indexOther = 0;
		indexTotal = 0;
		
		if (options["sidebar"] == true) {
			var container = $("#dyn-result");
			container.empty();
			searchResults = [];
			container = $("#pagelinks");
			container.empty();
			if (shops.length > 0)
				fillSidebar(0, shops.length);
		}
		if (options["markers"] == true) {
			map.clearOverlays();
			if (shops.length > 0)
				addMarkers(0, shops.length);
		}
	}
}

//*** UPDATE STORELOCATOR ***//
$(document).ready(function()
{
	$('a.close').click( function() {
      parent.$.fancybox.close();
   });
});
// *** UPDATE STORELOCATOR ***//
