/*
* Running routes 
* developed by in2Sports for ASICS // Geldermalsen 2006
* 
* thanks to walkjogrun.net and 'Beginning Google Maps Applications with PHP and Ajax, From Novice to Professional' 
* by M. Purvis, J.Sambells and C. Turner
*/
var DEBUG = 0;
var centerLongitude = 10.4515265;
var centerLatitude = 51.1656915;
var startZoom = 8;
var map = null;
var imagePath = "../themes/asics20/media/routes/";
var scriptPath = "../includes/googlemaps/";
var last2Points = [];
var http = null;
var nocookies = null;
var BGCOLOR_MO = "#cecece";
var LINECOLOR = "#ff0000";
var SITEURL = "";

var MILESASKM = 1.609344;
var icon = null;
var iconfinish = null;
var iconroute = null;
var map = null;
var newr = null;
var baseIcon = null;
var currentPoint = null;

var	currentX = null;
var	currentY = null;
var	currentZoom = 14;
var currentFile = "";
var geocoder;

// deprecated ; overal vervangen door object currentRoute
var currentRouteId = null;
var currentRouteName = "No name";
var currentRouteOwner = null;
var sortBy = 'date_creation';
var sortDir = 'DESC';
var offsetRouteList = 1;
var globalFilter = { type : null , label : "", waarde: null};
var globalSearchString = null;
var undefined;

// currentRoute als object
var currentRoute = {
											"id": null,
											"description": "",
											"underground": "",
											"distance": 0,
											"elevation": 0,
											"postalcode": "",
											"region": "",
											"placename": "",
											"countrycode": "",
											"rank": 0,
											"rank_counter": 0,
											"photo_url": "",
											"route": "",
											"private": "N",
											"avg_altitude" : 0,
											"waypoints" : [],
											toString : function () {
													this.description = typeof(this.description)=='string'?this.description:new String(""); 	
													this.postalcode =  typeof(this.postalcode)=='number'?this.postalcode.toString():(typeof(this.postalcode)=='string'?this.postalcode:new String("")); 	
													this.placename = typeof(this.placename)=='string'?this.placename:new String(""); 	
													this.region = typeof(this.region)=='string'?this.region:new String(""); 	
													this.countrycode = typeof(this.countrycode)=='string'?this.countrycode:new String(""); 	
											}
										};

var currentWaypoint  = {
					"id":null,
					"idx":0,
					"comment":"",
					"photo_upload": null,
					"photo_url": null,
					"latitude": 0,
					"longitude": 0,
					"gtopo30" : 0
			};

//user prefs
var currentUnit = "km";
var currentSpeed = 10;
var currentWeight = 190;
var minutesPerUnit = 60 / currentSpeed;
var altUnit = "miles";

var lastTab = null;
var lastTabLabel = null;
var lastSubTab = null;
var lastSubTabLabel = null;
var mileIcon = new Array();
var recording = false;

var route = [];
var elev8n = new Array();
var routeDistance = 0;
var request = null;
var env = "http://www.myasics.com/";
// de ingelogde gebruiker
var client_id = 0; 
var author_name = "";
// Een aantal filters die voor een deel gevoed worden via een Ajax call indien er gefilterd moet worden
var fOptionsSet = false;
var fRegion = [];
var fPlacename = [];
var fCountrycode = [];
var fUnderground = [];
var fEnvironment = [];
var fPostalcode  =[];

var aFilterKey    = new Array('distance', 'placename', 'region', 'underground', 'environment', 'rate');
var aFilter = new Array("distance", "place","Area", "Terrain", "Surrounding area","Rating");

var MY= 0;
var FIND= 1;
var MAKE= 2;
var ALL= 3;

var OVERVIEW=0;
var DETAIL=1;

var rrMODUS = MY; 
var rrROUTEVIEW = OVERVIEW;

/* handlers naar controls in map */
var toolbar = null;
var overViewMap = null;
var sidebar = null;
var largeMapControl = null;
var mapTypeControl = null;
/* calculator*/
var calc = null;
/* routeinfo window*/
var ri;

/* flickr photo bar */
var flickr_TYR = {
				'container' : 'flickrDiv' 
			,	'content' : 'flickrBody' 
			, 'gallery': null
			, 'latitude' : null
			, 'longitude' : null
			, 'radius' : 5
			, 'radius_units' : 'km'
	};

/* kaart modi */
var WIDE = 0;
var SMALL = 1;
var rrMAPVIEW = SMALL;
var sidebarMODUS = WIDE;

/* heeft iemand routes ofnie? */
var HAS_ROUTES=1;

/* verwijzing naar het hoogte plaatje */
var hPlot = null;

/* streetview hulp params */
var panoClient;
var panoGlobalData=null;
var streetview_TYR = null;

/*partnerfinder markers */
var HAS_PARTNERFINDER = true;
var pfMarkers = [];

/* max aantal routes in tabel tonen */
var MAX_IN_ROUTELIST = 13;

function load() {

// de maatwerk icons
	baseIcon = new GIcon();
	baseIcon.shadow = imagePath + "shadow.png";
	baseIcon.image = imagePath + "basic_marker.png";
	baseIcon.iconSize = new GSize(17, 17);
	baseIcon.shadowSize = new GSize(28, 17);
	baseIcon.iconAnchor = new GPoint(10, 10);
	baseIcon.infoWindowAnchor = new GPoint(5, 1);

	iconroute = new GIcon();
	iconroute.shadow = imagePath + "marker_shadow.png";
	iconroute.image = imagePath + "route_marker.png";
	iconroute.iconSize = new GSize(16, 16);
	iconroute.shadowSize = new GSize(30, 22);
	iconroute.iconAnchor = new GPoint(7, 16);
	iconroute.infoWindowAnchor = new GPoint(5, 1);

	icon = new GIcon(baseIcon);
	icon.image = imagePath + "mile_blank.png";

	base_marker = new GIcon(baseIcon);
	base_marker.image = imagePath + "basic_marker.png";
	base_marker.shadow = imagePath + "marker_shadow.png";
	base_marker.shadowSize = new GSize(30,22);
	base_marker.iconAnchor = new GPoint(7, 16);


	startIcon = new GIcon(baseIcon);
	startIcon.image = imagePath + "start.png";
	adIcon = new GIcon(baseIcon);
	adIcon.image = imagePath + "ad_img.gif";
	adIcon.iconSize = new GSize(40, 40);
	for (i=1;i<30;i++) {
		mileIcon[i] = new GIcon(baseIcon);
		mileIcon[i].image = imagePath + "mile_"+i+".png";
	}

	finishIcon = new GIcon(baseIcon);
	finishIcon.image = imagePath + "finish.png";

	flickrIcon = new GIcon(baseIcon);
	flickrIcon.shadow = imagePath + "flickr_marker_shadow.png";
	flickrIcon.image = imagePath + "flickr_marker.png";

	svIcon = new GIcon();
	svIcon.image = imagePath + "streetview_marker.png";
	svIcon.shadow = imagePath + "marker_shadow.png";
	svIcon.iconSize = new GSize(22, 22);
	svIcon.iconAnchor = new GPoint(10, 10);
	svIcon.infoWindowAnchor = new GPoint(5, 1);

	pfIcon = new GIcon();
	pfIcon.image = imagePath + "partner_marker.png";
	pfIcon.shadow = imagePath + "partner_marker_shadow.png";
	pfIcon.iconSize = new GSize(22, 22);
	pfIcon.iconAnchor = new GPoint(16, 16);
	pfIcon.infoWindowAnchor = new GPoint(10,10 );

				if (GBrowserIsCompatible()) {
								map = new GMap2(document.getElementById("map"));
								//map.setUIToDefault();

								/* zoom controle widget */
								largeMapControl = new GLargeMapControl3D(); 
								map.addControl(largeMapControl , new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(10,60)));

								/* maptype {map,satelite,hybrid} controle widget */
							 	mapTypeControl = new GMapTypeControl();
								map.addControl(mapTypeControl, new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(80, 60)));

								map.addControl(new RouteTabs());

								toolbar = new RouteToolbar();
								map.addControl(toolbar);

								map.addControl(new RouteStatus());
								sidebar = new RouteControls();
								map.addControl(sidebar);
								overViewMap = new GOverviewMapControl() ;
								map.addControl(overViewMap, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT,new GSize(10,10)));

								calc = new calculatorControl();
								map.addControl(calc);

								ri = new RouteInfo();
								map.addControl(ri);


								map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
								overViewMap.onclick = function () {
								}
								resizeMap();

					geocoder = new GClientGeocoder();
					
					/* volledig overgenome door RouteDraw
					GEvent.addListener(map, 'click', function(overlay, point) {
						if (overlay) {
							//do nothing 
						} else if (point && recording) {
							if (route.length == 0) {
							startRoute(point);
							doAjaxGetLocationInfo(point);
							lookupElevation(0);
						} else if (route[route.length-1].x != point.x && route[route.length-1].y != point.y) {

							if (route.length == 1) {
									melding("Now draw your route by clicking on all the waypoints up to and including the last one");
							}
							else {
									melding("Check all the points and then click on the SAVE icon.");
							}

							route.push(point);
							route[route.length-1].comment='-';
							route[route.length-1].fk_photo_id=0;

							lookupElevation(route.length-1);
							//This marks the route as saveable
							//currentRouteId = null;
							drawRoute(route);
						}
						}
					});
				*/

  			GEvent.addListener(map, "zoom", function() {
					initSearchFilter (); 
    			/*if (route.length == 0 && !recording)  */
    			if ((rrMODUS==ALL || rrMODUS==FIND) && rrROUTEVIEW==OVERVIEW) {
      				loadRoutes();
    			} else {
      			drawRoute(route);
    			}
  			});

				GEvent.addListener(map, "moveend", function() {
								var centerpoint = map.getCenter();
								centerLatitude = centerpoint.lat();
								centerLongitude = centerpoint.lng();
								initSearchFilter (); 
								/*if (route.length == 0 && !recording) */
    						if ((rrMODUS==ALL || rrMODUS==FIND) && rrROUTEVIEW==OVERVIEW) {
									loadRoutes();
								}
				});

					currentRoute.id = getURLParam('route_id');
					var tab  = getURLParam('tab');
					if (currentRoute.id >0) {
						ajaxCall("getClientID.php?1=1",responseClientID,1,0);
						doAjaxLoadRoute(currentRoute.id);	
						klapInUitFunctie('uit');
						if (tab == 'my')
								act_myRoutes('my');
					} 
					else {
						if (HAS_ROUTES==1) {
								act_myRoutes('my');
						}
						else
								act_allRoutes();
					}

				 //onresize event
				if (window.attachEvent) {
												 window.attachEvent("onresize",function(){ //IE
												 resizeMap()
				});
				 } else {
								 window.addEventListener("resize", function() {
								 resizeMap();
								 }, false);
				 }			
			} // einde compatible
			setTimeout('minimizeFooter()',10000);
			changeBodyClass('loading','standby');
} // einde load

/*
function repositionMapControls() {		

			if (largeMapControl != null) {
					map.removeControl(largeMapControl);
					map.removeControl(mapTypeControl);
			}
			largeMapControl = new GLargeMapControl(); 
			mapTypeControl = new GMapTypeControl();

			if (rrVIEW == WIDE) {
								map.addControl(largeMapControl , new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(10,50)));
								map.addControl(mapTypeControl, new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(10, 70)));
			}
			else {
								map.addControl(largeMapControl , new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(10,50)));
								map.addControl(mapTypeControl, new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(60, 50)));
			}
}
*/


function savePosition() {
	currLoc = map.getCenter();

	var getVars =  "?lat=" + currLoc.lat() + "&lng=" + currLoc.lng() + "&zoom=" + map.getZoom(); 
	var request = GXmlHttp.create();

	//open the request to storeMakres.php on your server
	request.open('GET', 'saveMapview.php' + getVars, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
				//document.getElementById('save_msg').innerHtml = request.responseText;		
				alert(request.responseText);
		}
	}
	request.send(null);
	return false;
}

function initSearchFilter () {
			globalFilter = { type : null , label : "", waarde: null};
			globalSearchString = null;
}


function resizeMap(){
var corrY = 151;
var corrX = 178;
var corrMapY = 28;

				 if (rrMAPVIEW == SMALL) {
						$('pagetitle').style.display = 'block';
						$('menu').style.display = 'block';
						$('mapcontainer').style.top = '151px';
				 }
				 else {
						$('pagetitle').style.display = 'none';
						$('menu').style.display = 'none';
						$('mapcontainer').style.top = '86px';
							corrY = 86;
							corrX = 0;
							corrMapY = 28;
				 }

				if (window.attachEvent) {
				 var hght=document.documentElement.clientHeight-corrY;
				 var width=document.documentElement.clientWidth-corrX;

				 document.getElementById("mapcontainer").style.height=hght+"px";
				 document.getElementById("mapcontainer").style.width=width+"px";
				 document.getElementById("map").style.height= (hght - corrMapY) +"px";
				 document.getElementById("sidebar").style.height=(hght-50)+"px";

				 document.getElementById("map").style.width=(width-15)+"px";
				 document.getElementById("tabsDiv").style.width=(width-15)+"px";
				 document.getElementById("toolsDiv").style.width=(width-15)+"px";
				} else {
								 //var ffHeight = parseInt(window.innerHeight*parseInt(window.innerHeight)-97)/parseInt(window.innerHeight);
								 var ffHeight = parseInt(parseInt(window.innerHeight)-corrY);
								 var ffWidth = parseInt(parseInt(window.innerWidth)-corrX);

								 document.getElementById("mapcontainer").style.height=ffHeight+"px";
								 document.getElementById("map").style.height= (ffHeight-corrMapY) +"px";
								 document.getElementById("sidebar").style.height=(ffHeight-50)+"px";

								 document.getElementById("mapcontainer").style.width=ffWidth+"px";
								 document.getElementById("map").style.width=(ffWidth-15)+"px";
								document.getElementById("tabsDiv").style.width=(ffWidth-15)+"px";
								document.getElementById("toolsDiv").style.width=(ffWidth-15)+"px";
				}
}

window.onload = load;
window.onunload = GUnload;


