window.addEvent('domready', function(){
	if (GBrowserIsCompatible()) {
		var startInitGmap = new Date().valueOf();
		
		/*start config googlemaps implementation*/
		
		var pathLocationInfo = gam.context+'/store/map_popup';
			
		
		//every shop will have a status porperty.. now 0 means normal and so on
		var adapterStatus = {
				normal:"REGULAR",
				opensunday:"OPEN_SUNDAY",
				shortly:"OPENS_SHORTLY",
				tempclosed:"CLOSED_TEMPORARILY",
				recently:"RECENTLY_OPENED"
			}

		var offsetXinfoWindow = 16; //the offset of the infowindow next to the marker horizontally
		var offsetYinfoWindow = 87;//the offset of the infowindow next to the marker vertically
		
		var defaultZoomLevelOneLocation = 13;
		var defaultZoomLevelAllLocations = 7;
		var centerAllLocations = new GLatLng(52.309822,5.421753);//center of the netherlands
		
		var bolZoomOnClick = true;//zoom in on region when clicking a marker
		var minZoomLevelOnClick = 9;//minimum zoomlevel to zoom into when a marker is clicked
		
		
		/*end config googlemaps implementation*/
		
		//some 'global' variables for the gmap
		var currentInfoWindow = null;
		var currRedrawTimeOut = null;
		
		//baseIcon to clone for every marker
		var baseIcon = new GIcon({
			iconSize : new GSize(16, 16),
			iconAnchor : new GPoint(8, 8),
			infoWindowAnchor : new GPoint(5, 1)
		});
		
		var zoomedBaseIcon = new GIcon({
			iconSize : new GSize(37, 37),
			iconAnchor : new GPoint(10, 10),
			infoWindowAnchor : new GPoint(5, 1)
		});
		
		
		//custom overlay class for custom info window
		var gamInfoPopUp = function(marker) {
		  this.marker = marker;
		}
		gamInfoPopUp.prototype = new GOverlay();
		gamInfoPopUp.prototype.initialize = function(map) {
	
			var popUpWindow = new Element('div', {
			  'class': 'popup',
			  'id':'testid',	
			  'html': '<div class="top"></div><div class="mid"><div class="right"><a href="#" class="close">Close</a></div><div class="popup-box"><div class="cont-popup-box-loading"><img src="'+gam.pathStaticData+'images/loader.gif" class="loading" /></div></div></div><div class="bot"></div>',
			  'styles': {
			      'left':10,
			      overflow:'hidden'
			  }
			});
	
			new Request({
				url: pathLocationInfo +'?random='+Math.random(),
				noCache: true,
				method: 'get',
				data:{storeid:this.marker.locationId},
				onSuccess:function(responseText, responseXML){
					var contentContainer = popUpWindow.getElement(".popup-box");
					
					if(Browser.ie && Browser.version < 7){ //ie6 so no fancy stuff
						var oldHeight = popUpWindow.offsetHeight;
						contentContainer.set('html', responseText);
						var newHeight = popUpWindow.offsetHeight;
						popUpWindow.setStyles({top:parseInt(popUpWindow.style.top,10)+(oldHeight-newHeight)})
					}
					else {//no ie6 so let's have some animation
						var oldHeight = popUpWindow.offsetHeight;
						var oldTop = parseInt(popUpWindow.style.top,10);
						var waitContentHeight = contentContainer.offsetHeight; 

						popUpWindow.setStyles({height:oldHeight})
						contentContainer.set('html', responseText);

						var infoContentHeight = contentContainer.scrollHeight;
						var newHeight = oldHeight + (infoContentHeight-waitContentHeight) 
						var newTop = oldTop - (infoContentHeight-waitContentHeight)

						var slideFX = new Fx.Morph(popUpWindow, {duration: 'short', transition: Fx.Transitions.Sine.easeOut});
						slideFX.start({
							'height': [oldHeight, newHeight],
							'top': [oldTop, newTop]
						});
					}
					  
				 },
				onFailure:function(){
					 var contentContainer = popUpWindow.getElement(".popup-box");
					 contentContainer.set('html', "<span class='error'>fout: informatie niet beschikbaar</span>");
				 }
			}).send();
	
			  
			popUpWindow.getElement(".close").addEvent("click",function(){closeOverlay(true)})
		
			this._map = map;
			this._div = popUpWindow;
		
			map.getPane(G_MAP_FLOAT_PANE).appendChild(popUpWindow);  
		}
		
		gamInfoPopUp.prototype.remove = function(){
		  this._div.parentNode.removeChild(this._div);
		}
		
		gamInfoPopUp.prototype.redraw = function() {}
		
		gamInfoPopUp.prototype.positionPopup = function() {
		  this._div.setStyles({
			  top:(this._map.fromLatLngToDivPixel(this.marker.getPoint()).y - this._div.offsetHeight),
			  left:(this._map.fromLatLngToDivPixel(this.marker.getPoint()).x - (this._div.offsetWidth/2) + 10),
			  visibility: 'visible'
		  });
		}
		
		function closeOverlay(bolAnimate) {
			if (currentInfoWindow) {
				  if(!bolAnimate){
					  map.removeOverlay(currentInfoWindow);
				  }
				  else{
					  var fade = new Fx.Morph(currentInfoWindow._div, {duration: 'short', transition: Fx.Transitions.Sine.easeOut,complete :function(){alert("!")}});
					  fade.start({
					      'height': [currentInfoWindow._div.offsetHeight, 0]
					  });
				  }
			}
		}

		//initializes the map
		var map = new GMap2(document.getElementById("sfp-gmap-container"));

		//build icons to clone
		var arrIcons = []
        arrIcons[adapterStatus.normal] = new GIcon(baseIcon);
		arrIcons[adapterStatus.normal].image = gam.pathStaticData+"images/icon_bouwmarkt_m.gif";
        arrIcons[adapterStatus.opensunday] = new GIcon(baseIcon);
		arrIcons[adapterStatus.opensunday].image = gam.pathStaticData+"images/icon_zondagasopen_m.gif";
		arrIcons[adapterStatus.shortly] = new GIcon(baseIcon);
		arrIcons[adapterStatus.shortly].image = gam.pathStaticData+"images/icon_binnenkortopen_m.gif";
        arrIcons[adapterStatus.tempclosed] = new GIcon(baseIcon);
		arrIcons[adapterStatus.tempclosed].image = gam.pathStaticData+"images/icon_tijdelijkgesloten_m.gif";
        arrIcons[adapterStatus.recently] = new GIcon(baseIcon);
		arrIcons[adapterStatus.recently].image = gam.pathStaticData+"images/icon_nieuwegammabouwmarkt_m.gif";
		
		var arrIcons2 = []
		
		arrIcons2[adapterStatus.normal] = new GIcon(zoomedBaseIcon);
		arrIcons2[adapterStatus.normal].image = gam.pathStaticData+"images/icon_bouwmarkt_g.gif";
		arrIcons2[adapterStatus.opensunday] = new GIcon(zoomedBaseIcon);
		arrIcons2[adapterStatus.opensunday].image = gam.pathStaticData+"images/icon_zondagasopen_g.gif";
		arrIcons2[adapterStatus.shortly] = new GIcon(zoomedBaseIcon);
		arrIcons2[adapterStatus.shortly].image = gam.pathStaticData+"images/icon_binnenkortopen_g.gif";
		arrIcons2[adapterStatus.tempclosed] = new GIcon(zoomedBaseIcon);
		arrIcons2[adapterStatus.tempclosed].image = gam.pathStaticData+"images/icon_tijdelijkgesloten_g.gif";
        arrIcons2[adapterStatus.recently] = new GIcon(zoomedBaseIcon);
		arrIcons2[adapterStatus.recently].image = gam.pathStaticData+"images/icon_nieuwegammabouwmarkt_g.gif";
		
		if(gamLocations.view=="storelocation" && gamLocations.show && gamLocations.show.length==1){
			
			for (var i = gamLocations.all.length-1; i >= 0; i--) {
				if(gamLocations.all[i].id==gamLocations.show[0].id){
					arrIcons["storelocation"] = arrIcons2[(gamLocations.all[i].status?gamLocations.all[i].status:adapterStatus.normal)];
					arrIcons2["storelocation"] = arrIcons["storelocation"];
					gamLocations.all[i].status="storelocation";
					break;
				}
			}
			var detailPage = true;
			//map.setMapType(G_SATELLITE_MAP);
		}
		
        GEvent.addListener(map, "zoomend", function(){
    		if (currentInfoWindow) {
    			currentInfoWindow.positionPopup();
    		}
    	});
        map.setUIToDefault();
        map.disableScrollWheelZoom();
        var mapManager = new GMarkerManager(map,{trackMarkers:true});
        
        //add the markers to google maps
		for (var i = gamLocations.all.length-1; i >= 0; i--) {
            var point = new GLatLng(gamLocations.all[i].lat,gamLocations.all[i].lon);
            var marker = new GMarker(point,{icon:arrIcons[(gamLocations.all[i].status?gamLocations.all[i].status:adapterStatus.normal)],title:gamLocations.all[i].name});
            marker.locationId = gamLocations.all[i].id;
            value = (gamLocations.all[i].status?gamLocations.all[i].status:adapterStatus.normal);
            var markerZoomed = new GMarker(point,{icon:arrIcons2[(gamLocations.all[i].status?gamLocations.all[i].status:adapterStatus.normal)],title:gamLocations.all[i].name});
            markerZoomed.locationId = gamLocations.all[i].id;
            
            GEvent.addListener(marker, "click", function() {
            	if (currentInfoWindow!=null) {
                  closeOverlay(false);
                }
            	var currZoom = bolZoomOnClick?Math.max(map.getZoom(),minZoomLevelOnClick):map.getZoom(); 
            	map.setZoom(currZoom)
            	var mapproj = map.getCurrentMapType().getProjection();
            	var markerGpoint = mapproj.fromLatLngToPixel(new GLatLng(this.getPoint().lat(), this.getPoint().lng()),currZoom);
            	var newCenterMap = mapproj.fromPixelToLatLng(new GPoint(markerGpoint.x,markerGpoint.y-100),currZoom);
                map.panTo(newCenterMap);
            	//if (!this.overlay) {
                  this.overlay = new gamInfoPopUp(this);
                //}
                currentInfoWindow = this.overlay;
                map.addOverlay(this.overlay);
                this.overlay.positionPopup(true)
              });
            
            GEvent.addListener(markerZoomed, "click", function() {
            	if (currentInfoWindow!=null) {
                  closeOverlay(false);
                }
            	var currZoom = bolZoomOnClick?Math.max(map.getZoom(),minZoomLevelOnClick):map.getZoom(); 
            	map.setZoom(currZoom)
            	var mapproj = map.getCurrentMapType().getProjection();
            	var markerGpoint = mapproj.fromLatLngToPixel(new GLatLng(this.getPoint().lat(), this.getPoint().lng()),currZoom);
            	var newCenterMap = mapproj.fromPixelToLatLng(new GPoint(markerGpoint.x,markerGpoint.y-100),currZoom);
                map.panTo(newCenterMap);
            	//if (!this.overlay) {
                  this.overlay = new gamInfoPopUp(this);
                //}
                currentInfoWindow = this.overlay;
                map.addOverlay(this.overlay);
                this.overlay.positionPopup(true)
              });
            
            if(detailPage === true){
//            	mapManager.addMarker(marker,0,17);
            	mapManager.addMarker(marker,0,9);
            	mapManager.addMarker(markerZoomed,10,17);
            }else{
            	mapManager.addMarker(marker,0,9);
            	mapManager.addMarker(markerZoomed,10,17);
            }
            //map.addOverlay(marker);
        }
		
		if(!gamLocations.show || gamLocations.show.length<1){//no show array specified so show all locations
			map.setCenter(centerAllLocations, gamLocations.zoom?gamLocations.zoom:defaultZoomLevelAllLocations);	
		}
		else if(gamLocations.show.length==1){//show one location
			map.setCenter(new GLatLng(gamLocations.show[0].lat,gamLocations.show[0].lon), gamLocations.zoom?gamLocations.zoom:defaultZoomLevelOneLocation);
		}
		else {//show more than one location
			var latMin = gamLocations.show[0].lat;
			var latMax = gamLocations.show[0].lat;
			var lonMin = gamLocations.show[0].lon;
			var lonMax = gamLocations.show[0].lon;
			for(var i=gamLocations.show.length-1;i>0;i--){
				latMin = Math.min(latMin,gamLocations.show[i].lat);
				latMax = Math.max(latMax,gamLocations.show[i].lat);
				lonMin = Math.min(lonMin,gamLocations.show[i].lon);
				lonMax = Math.max(lonMax,gamLocations.show[i].lon);
			}
			
			var spacer = 0.00025;
			latMin -= spacer;
			latMax += spacer;
			lonMin -= spacer;
			lonMax += spacer;
			
			var markersBound = new GLatLngBounds(new GLatLng(latMin,lonMin),new GLatLng(latMax,lonMax));
			map.setCenter(new GLatLng((latMin+0.5*(latMax-latMin)),(lonMin+0.5*(lonMax-lonMin))), gamLocations.zoom?gamLocations.zoom:map.getBoundsZoomLevel(markersBound));
		}
		
		if(document.getElementById("yourRouteForm")){
			var directions=null; 
			
			$("yourRouteForm").addEvent("submit",function(){
				if(directions!=null)directions.clear();
				//document.getElementById("routeInstructionsContainer").innerHTML ="";
				directions = new GDirections(map,document.getElementById("routeInstructionsContainer"));
				GEvent.addListener(directions,"error", function() {
					$("routeInstructions").setStyle("display", "none");
					$("errorTips").setStyle("display", "block");
					$("errorText").innerHTML="De locatie '" + $("postcodeUser").get("value") + "' is niet bekend.";
					$("postcodeUser").getParent().addClass("fault");
					//var googleWin = window.open("http://maps.google.nl?&saddr="+$("postcodeStore").get("value")+" ,netherlands"+"&daddr="+$("postcodeUser").get("value")+" ,netherlands","_blank");
				})
				GEvent.addListener(directions,"load", function() {
					$("postcodeUser").getParent().removeClass("fault");
					$("errorTips").setStyle("display", "none");
					$("errorText").innerHTML = "";
					$("routeInstructions").setStyle("display", "block");
				})
				$("postcodeUser").set("value", $("postcodeUser").get("value").replace(/\b([0-9][0-9][0-9][0-9])\s*([A-Za-z][A-Za-z])\b/, "$1$2"));
				
				directions.load("from: "+$("postcodeUser").get("value")+" ,netherlands to: "+$("postcodeStore").get("value")+", netherlands",{locale:"nl"});
				
				//map.setMapType(G_NORMAL_MAP);
				return false;
			});
			
			if($("printRouteInstructions")){
				$("printRouteInstructions").onclick =  function(){
					//this link looks nice but doesn't automatically open the print dialogue
					//var printWindow = window.open("http://maps.google.nl?&saddr="+$("postcodeStore").get("value")+" ,netherlands"+"&daddr="+$("postcodeUser").get("value")+" ,netherlands&z=10&pw=2","_blank");
					var printWindow = window.open("/static/html/print_route_instructions.html","_blank", "width=800,height=600");
				};
			}
			
		}
		window.addEvent('onunload',GUnload);  
      }
	
	//console.log("init gmaps: "+(new Date().valueOf()-startInitGmap))
})

Tabs = {}
Tabs.ShowTabContent = function(counter){

	if(counter == 0){
		var Panel = $('tab-0');
		var PanelDis = $('tab-1');
		var li = $('li-0');
		var liDis = $('li-1');
	}
	else {
		var Panel = $('tab-1');
		var PanelDis = $('tab-0');
		var li = $('li-1');
		var liDis = $('li-0');
	}
	PanelDis.removeClass("active");
	PanelDis.removeClass("display");
    Panel.addClass("display");
    Panel.addClass("active");
    liDis.removeClass("active");
	li.addClass("active");
}

