/*
   Author: Steve Digirolamo - Caspio
   Email: steve.digirolamo@caspio.com
   Url: http://caspio.com
   Version 1.0 Date Created 6/13/07
   API versisons used google maps API version 2.x (2.74 as of writing this) and Yahoo 3.4 
   
   Description: Configurable yahoo/google maps mashup built into one for use with Caspio Bridge datapages.
   
   Example / Instructions for deployment
   
   REQUIREMENTS:
   		* You must have access to a webserver to deploy your caspio bridge page.
		* Your page being served must contain a body onLoad event handler like so <body onLoad="loadMap(mapType,mapWidth,mapHeight)">
			** If your page already has the onLoad event handler please add loadMap at the end of the function calls
		* A google maps or yahoo maps API key depending upon which version you wish to use.
		* You will include your yahoo or google maps js library functions include along with this js file at the very bottom of your page.
		  Make sure to place these right above the </body> tag
*/
    //global variable declaration
	var map 		= null;
    var geocoder 	= null;
	
	var mapType 	= detectMapType();
	var plotMulti 	= 'N';
        var YMap = null;	
	//if(document.getElementById('mapType')){ mapType = document.getElementById('mapType').innerHTML.toString().replace(/^\s+|\s+$/g, '');}
	if(document.getElementById('mapWidth')){ var mapWidth = document.getElementById('mapWidth').innerHTML.toString().replace(/^\s+|\s+$/g, '');}
	if(document.getElementById('mapHeight')){ var mapHeight = document.getElementById('mapHeight').innerHTML.toString().replace(/^\s+|\s+$/g, '');}
	if(document.getElementById('plotMulti')){ plotMulti = document.getElementById('plotMulti').innerHTML.toString().replace(/^\s+|\s+$/g, '');}

	if(document.getElementById('dp')){
		var detailsPage	= document.getElementById('dp').innerHTML.toString().replace(/^\s+|\s+$/g, '');
	}
		
/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	load function is called after the page has fully loaded. this function is automatically called when the browser DOM
	finishes loading. The webpage where the map is automatically embedded right above where you place your caspio datapage embed.
	
	*this function is the heart of the mapping mashups and this line of code must be included for anything to work properly.
	
	<body onLoad="loadMap(mapType,mapWidth,mapHeight)">
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function loadMap(mapType,mapWidth,mapHeight) {
      if (typeof mapType == 'undefined' ) mapType = 'G';
	  if (typeof mapWidth == 'undefined' ) mapWidth = 0;
	  if (typeof mapHeight == 'undefined' ) mapHeight = 0;
	 
	  //check to make sure the map container div does not exist
	  if(!document.getElementById('map')){
		  mapContainer = document.createElement('div');
		  mapContainer.setAttribute("id","map");
		
		  var startofCaspio = document.getElementById("caspioform");
		  var parentDiv = startofCaspio.parentNode;
	
		  parentDiv.insertBefore(mapContainer, startofCaspio);
	  } else {
		  mapContainer = document.getElementById('map');
	  }
			
	  mapContainer.style.width = mapWidth;
	  mapContainer.style.height = mapHeight;
	
	 	  if(mapType.toUpperCase() == 'G'){ //google map selected
			 window.onUnload = GUnload();
			 if (GBrowserIsCompatible()) {
				
				map = new GMap2(document.getElementById("map"));
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				geocoder = new GClientGeocoder(); 
				
				if(document.getElementById('home_position')){
					var startPOS = document.getElementById('home_position').innerHTML;
				} else {
					var startPOS = null;
				}
				geocoder.getLatLng(startPOS,function(point){
					if(!point){
						map.setCenter(new GLatLng(36.90, -105.05), 2); //this is a default map position (kansas) if we cant find geo coordinates
						 if(!detailsPage && plotMulti.toUpperCase() == 'Y' ){ 
						 	plotAllG();
						 } 
					} else {
						map.setCenter(point,3);
						if(!detailsPage && plotMulti.toUpperCase() == 'Y'){ 
							plotAllG();
						}
					}
				}
				);
			  
			  }
		  } else { // default map to yahoo
				map = new YMap(document.getElementById('map'));
				
				if(document.getElementById('home_position')){
					startPoint = document.getElementById('home_position').innerHTML
				} else {
					startPoint = new YGeoPoint(36.90, -105.05);
				}
				
				map.drawZoomAndCenter(startPoint, 9);
				map.addTypeControl();
				map.addZoomLong();
				
				// Set map type to either of: YAHOO_MAP_SAT YAHOO_MAP_HYB YAHOO_MAP_REG
				map.setMapType(YAHOO_MAP_REG);
				
				//Get valid map types, returns array [YAHOO_MAP_REG, YAHOO_MAP_SAT, YAHOO_MAP_HYB]
				var myMapTypes = map.getMapTypes();
				if(!detailsPage){ plotAllY(); }
			  
		  }
	  
		  if(detailsPage){ 
			  var address 	= null;
			  var id 		= null;
			  var zoomLevel = 1;
			  var icon	 	= null;
			  
			  if(document.getElementById('locAddress')) { address = document.getElementById('locAddress').innerHTML; }
			  if(document.getElementById('idAddress')) { id = document.getElementById('idAddress').innerHTML; }
			  if(document.getElementById('mapIcon')) { icon = document.getElementById('mapIcon').innerHTML; }
		
			  showAddress(address,id,zoomLevel,icon);
		  }
	}
	
/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	plotAllG (google maps implementation) gets all addresses from the given caspio datapage using a defined html tag called "tt"
	this tag needs to be defined in a custom html block in order to plot all points.
	example: <tt>[@field:fieldnameofaddressinyourtable]</tt>
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function plotAllG(){
		managepoints 	= new GMarkerManager(map);
		allpoints 	 	= document.getElementsByTagName('tt'); 
		var marker 		= null;
				
		if(document.getElementById('mapIcon')){
			var icon = document.getElementById('mapIcon').innerHTML;
			icon = 'https://bridge.caspio.net/images/icons/pointers/icon' + icon.toString().replace(/^\s+|\s+$/g, '') + '.gif';
		} else {
			var icon = '';;
		}
		
		var theIcon 				= new GIcon(G_DEFAULT_ICON,icon);
		theIcon.iconSize 			= new GSize(20,34);
		theIcon.iconAnchor 			= new GPoint(10,10);
		theIcon.infoWindowAnchor 	= new GPoint(15,15);
		
		
		for (i=0;i<allpoints.length;i++) {
			geocoder.getLatLng(allpoints[i].innerHTML,
			function(point) {
			  if (!point) {
				//address not found continue on
			  } else {
				marker = new GMarker(point,{icon:theIcon});
				managepoints.addMarker(marker,1);
			  }
			}
		  );
		}

		managepoints.refresh();
	}

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	plotAllY (yahoo maps implementation) gets all addresses from the given caspio datapage using a defined html tag called "tt"
	this tag needs to be defined in a custom html block in order to plot all points.
	example: <tt>[@field:fieldnameofaddressinyourtable]</tt>
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function plotAllY(){
		allpoints 	= document.getElementsByTagName('tt'); 
		
		if(document.getElementById('mapIcon')){
			var icon = document.getElementById('mapIcon').innerHTML;
			icon = 'https://bridge.caspio.net/images/icons/pointers/icon' + icon.toString().replace(/^\s+|\s+$/g, '') + '.gif';
		} else {
			var icon = '';;
		}
		
		var theIcon = new YImage(icon, new YSize(20,34));
		
		for (i=0;i<allpoints.length;i++) {
			 map.addOverlay(new YMarker(allpoints[i].innerHTML,theIcon));
		}
	}
	
/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	showAddress is designed to plot the point on the map and zoom in for a better view. Parameters are as follows:
	address :: string representing the location
	id :: unique (autonumber) field in caspio table
	zoomLevel :: 1-16 :: 1 = most zoomed in for yahoo and least zoomed in for google
	icon :: icon to represent the marker (1-10) as according to capsio icons
	
	this function will automatically call showAddressY to plot points on the yahoo map if yahoo is determined to be the 
	current map type.
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function showAddress(address,id,zoomLevel,icon) { //add the ability to pass description and icon
		if (typeof zoomLevel == 'undefined' ) zoomLevel = 15;
		if (typeof icon == 'undefined' ) icon = 1;
		if (typeof id == 'undefined' )id = '';
		infoWindowText = '';
				
		if(mapType.toUpperCase() == 'G'){
			if(document.getElementById('iconDesc'+id)){ infoWindowText = document.getElementById('iconDesc' +id).innerHTML.toString().replace(/^\s+|\s+$/g, '');}
			if(infoWindowText != ''){ infoWindowText = unescape(infoWindowText);} else { infoWindowText = address; }
			
			geocoder.getLatLng(address,
				function(point) {
				  if (!point) {
					alert(address + " not found");
				  } else {
					var theIcon = new GIcon();
					theIcon.image = 'http://bridge.caspio.net/images/icons/pointers/icon' + icon + '.gif';
					theIcon.iconSize = new GSize(20,34);
					theIcon.iconAnchor =  new GPoint(10,10);
					theIcon.infoWindowAnchor =  new GPoint(10,10);
													
					var marker = new GMarker(point,{icon:theIcon});
					map.setZoom(5);	
					map.clearOverlays();
					map.addOverlay(marker);
					marker.openInfoWindowHtml('<div style="width:300px;height:50px;border:0px;background-color=#ffffff">'+infoWindowText+'</span>');
				  }
				}
			  );
		} else {
			showAddressY(address,id,zoomLevel,icon);
		}
	}

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function will be called from showAddress if yahoo is determined map type
	variables
	address :: string representing the location
	id :: unique (autonumber) field in caspio table
	zoomLevel :: 1-16 :: 1 = most zoomed in for yahoo and least zoomed in for google
	icon :: icon to represent the marker (1-10) as according to capsio icons
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function showAddressY(address,id,zoomLevel,icon) {
		map.removeMarkersAll();
		var infoWindowText = '';
				
		if(document.getElementById('iconDesc'+id)){ infoWindowText = document.getElementById('iconDesc' +id).innerHTML.toString().replace(/^\s+|\s+$/g, '');}
		if(infoWindowText != ''){ 
			infoWindowText = unescape(infoWindowText); 
		} else { 
			infoWindowText = address; 
		}
		
		if(document.getElementById('mapIcon')){
			var icon = document.getElementById('mapIcon').innerHTML;
			icon = 'https://bridge.caspio.net/images/icons/pointers/icon' + icon.toString().replace(/^\s+|\s+$/g, '') + '.gif';
		} else {
			var icon = '';;
		}
		
		var theIcon = new YImage(icon, new YSize(20,34), new YCoordPoint(10,25));
	 	var marker = new YMarker(address,theIcon);
	
		marker.openSmartWindow('<div style="width:300px;border:0px">'+ infoWindowText +'</div>');
		map.addOverlay(marker);
		map.drawZoomAndCenter(address,1);
	}

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function detectMapType
	fixes issue when using a defined search criteria setup
	
*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	function detectMapType(){
		scriptTags = document.getElementsByTagName('script');
		if(document.getElementById('mapType')){ return document.getElementById('mapType').innerHTML.toString().replace(/^\s+|\s+$/g, ''); }
		for(i=0;i<scriptTags.length;i++){
			if(scriptTags[i].src.toString().indexOf('api.maps.yahoo.com') >= 0){
				return 'Y';
				break;
			}
			if(scriptTags[i].src.toString().indexOf('maps.google.com') >= 0){
				return 'G';
				break;
			}
		}
		return 'Y';
	}

