// JavaScript Document
// scripts for interacting with mapquest and searching for stores

	var resultPoint = null;
	var myMap = null;
    var queryUrl = "";    
	var myIcon=new MQA.Icon("http://www.epicureancs.com/images/icons/ecsmapicon.png",30,24);
	
    var HOST_URL = 'http://www.mapquestapi.com';
    var APP_KEY = 'Fmjtd%7Cluu720uand%2C8x%3Do5-5z7l5';
    // var APP_KEY = 'Dmjtd%7Cluu720urn1%2C8x%3Do5-5z7sg';
	// dev key 'Dmjtd%7Cluu720urn1%2C8x%3Do5-5z7sg';
 	var SAMPLE_POST = HOST_URL + '/search/v1/FUNCTION?key=YOUR_KEY_HERE&callback=renderBasicSearchNarrative';
    var advancedOptions = HOST_URL + '/search/v1/radius?key=YOUR_KEY_HERE&callback=renderecsStoreSearchResults&ambiguities=ignore';
    var searchType = '';

// Load a blank map initially
function showInitialMap(){
	var divMap = document.getElementById("ecsStoreMap");
	divMap.innerHTML = "";
	if(divMap){
		window.mapExampleOne = new MQA.TileMap(divMap);
		//give zoom control
		MQA.withModule('zoomcontrol3', 'viewcontrol3', 'directions', 'shapes', 'route', function() {
			mapExampleOne.addControl(new MQA.LargeZoomControl3(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5, 5)));
			mapExampleOne.addControl(new MQA.ViewControl3(),new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT));
		});
        // dumpProps(response);
	    // processResults(response, window.mapExampleOne);
		divMap.style.display = "";
	 }
	}

// generates search url based of form fields and inserts value into an element to pass to mapquest		
function showEcsSearchURL() {
	var advancedOptions = HOST_URL + '/search/v1/radius?key=YOUR_KEY_HERE&callback=renderecsStoreSearchResults';
    // advancedOptions = advancedOptions;
	var origin = document.getElementById("e1_origin").value;
	var radius = document.getElementById("e1_radius").value;
	var maxMatches = document.getElementById("e1_maxMatches").value;
	var inFormat = document.getElementById('e1_inFormat').value;
	// inFormat = inFormat.options[inFormat.selectedIndex].value;
    if (inFormat == 'kvp') {
    // advancedOptions += "&ambiguities=ignore";
		advancedOptions += "&origin=" + origin + "&hostedData=MQA.MQ_87028_ecs,,I,Address,City,State,Postal,StoreName,phone";
		if(radius != ""){
			advancedOptions += "&radius=" + radius;
		}
		if(maxMatches != ""){
			advancedOptions += "&maxMatches=" + maxMatches;
		}
    } else if (inFormat == 'json') {
        advancedOptions += '&inFormat=json';
		
        advancedOptions += "&json=";
        var jsonText = '{';
		origin = origin.split(",");
		if (!isNaN(origin[0]) && !isNaN(origin[1]) && origin.length == 2) {
			jsonText += "origin:{latLng:{lat:" + origin[0] + ",lng:" + origin[1] + "}},";

		}
		else {
			jsonText += "origin:\"" + origin+ "\",";
		}
		jsonText += "hostedDataList:[{name:\"MQA.MQ_87028_ecs\", extraCriteria:\"\", fields:[\"I\", \"Address\", \"City\", \"State\", \"Postal\", \"StoreName\", \"phone\"]}]"
		var spacer = false;
        jsonText += ",options:{";
		if(radius != ""){
			if(spacer) jsonText += ", ";
			jsonText += "radius:" + radius;
			spacer = true;
		}
		if(maxMatches != ""){
			if(spacer) jsonText += ", ";
			jsonText += "maxMatches:" + maxMatches
			spacer = true;
		}
        jsonText += '}';
        jsonText += '}';
        advancedOptions += jsonText;
        
		queryUrl = advancedOptions;
		
    } else if (inFormat == 'xml') {
        advancedOptions += '&inFormat=xml';

        advancedOptions += "&xml=";
        var xmlText = '<search>';
		origin = origin.split(",");
		if (!isNaN(origin[0]) && !isNaN(origin[1]) && origin.length == 2) {
			xmlText += "<origin><latLng><lat>" + origin[0] + "</lat><lng>" + origin[1] + "</lng></latLng></origin>";
		}
		else {
			xmlText += '<origin>'+ origin + '</origin>';
		}
		xmlText += '<hostedDataList><hostedData><name>MQA.NTPois</name><extraCriteria>T=\'3016\'</extraCriteria><fields><field>I</field><field>T</field><field>Food</field><field>Address</field><field>City</field><field>State</field><field>Country</field><field>Phone</field></fields></hostedData></hostedDataList>'
        xmlText += '<options>';
		if(radius != ""){
			xmlText += "<radius>" + radius + "</radius>";
		}
		if(maxMatches != ""){
			xmlText += "<maxMatches>" + maxMatches + "</maxMatches>";
		}
        xmlText += '</options>';
		
        xmlText += '</search>'
        advancedOptions += xmlText;
    }
    var safe = advancedOptions;
    document.getElementById('exampleOneUrl').innerHTML = safe.replace(/</g, '&lt;').replace(/>/g, '&gt;');;
};

// iterate over search results and plot them on the map
function processResults(response, map){
	map.removeAllShapes();
	response = decompress(response);
	// dumpProps(response);
	var maxLat = -95, minLat = 95;
	var maxLng = -190, minLng = 190;
	if(response.origin){
	    // place marker at origin
		var originPOI = new MQA.Poi(response.origin.latLng);	
		originPOI.setInfoTitleHTML('Your location');
		originPOI.setInfoContentHTML('');
		map.addShape(originPOI);
		// IE issues with circle...
		// circle the search radius
		/*var circle = new MQA.CircleOverlay();
		circle.fillColor = "#e0e0e0";
		circle.fillColorAlpha = .4;
		circle.setShapePoints([response.origin.latLng.lat, response.origin.latLng.lng]);
		circle.radiusUnits = response.options.units;
		circle.radius = response.options.radius;
		map.addShape(circle);*/
	}
	
	if(response.boundingBox){
		var ulLat = response.boundingBox.ul.lat;
		var ulLng = response.boundingBox.ul.lng;
		var lrLat = response.boundingBox.lr.lat;
		var lrLng = response.boundingBox.lr.lng;
		
		var rectangle = new MQA.RectangleOverlay();	
		rectangle.fillColor = "#e0e0e0";
		rectangle.fillColorAlpha = .4;
		rectangle.setShapePoints([ulLat, ulLng, lrLat, lrLng]);
		map.addShape(rectangle);
	}
	
	if(response.polygon){
		var poly = new MQA.PolygonOverlay();
		poly.fillColor = "#e0e0e0";
		poly.fillColorAlpha = .4;
		poly.setShapePoints(response.polygon);
		map.addShape(poly);
	}
	
	if(response.line){
		var line = new MQA.LineOverlay();	
		line.fillColor = "#e0e0e0";
		line.fillColorAlpha = .4;
		line.setShapePoints(response.line);
		map.addShape(line);
	}
	
	if(response && response.info && parseInt(response.info.statuscode)==0 && response.searchResults){
		for(var i=0; i < response.searchResults.length; i++){
			if(response.searchResults[i]){
				var searchResult = response.searchResults[i];
				if(searchResult.shapePoints){
					for(var j=0; j < searchResult.shapePoints.length; j+=2){
						if(searchResult.shapePoints[j] > maxLat)
							maxLat = searchResult.shapePoints[j];
						if(searchResult.shapePoints[j] < minLat)
							minLat = searchResult.shapePoints[j];
						if(searchResult.shapePoints[j+1] > maxLng)
							maxLng = searchResult.shapePoints[j+1];
						if(searchResult.shapePoints[j+1] < minLng)
							minLng = searchResult.shapePoints[j+1];
					}
				}
				var shape = this.constructSearchResult(searchResult);			    
				// dumpProps(response);
				// dumpProps(shape);
				// dumpProps(response.origin.latLng);
				// Gets origin lat and lng to pass to directions link
				// alert('Lat: ' + response.origin.latLng.lat + 'Lng: ' + response.origin.latLng.lng);
               var origin_coords = response.origin.latLng.lat + ',' + response.origin.latLng.lng;
			   var destination_coords = shape.latLng.lat + ',' + shape.latLng.lng;
				// 47.0961,-91.6659				
				// dumpProps(searchResult);
				shape.setRolloverContent('<p class="ecs_store_hover_title">'+searchResult.fields.StoreName +'</p>');
				shape.setInfoTitleHTML('<p class="ecs_store_title">'+searchResult.fields.StoreName +'</p>');
                // build content 
				var infoBoxContent = '<p class="ecs_store_description">' + searchResult.fields.Address  + '<br />';
				infoBoxContent += searchResult.fields.City + ', ' + searchResult.fields.State + ' ' + searchResult.fields.Postal;
				// check for phone #
				if(searchResult.fields.phone){
				infoBoxContent += '<br /><strong>Phone:</strong> ' + searchResult.fields.phone;
 				  }				  


				// commented out for now until we decide to implement directions
				// infoBoxContent += '<br /><a onclick=\"getDirections(\''+ origin_coords + '\', \''+ destination_coords +'\'); return false;\" class="driving-directions" href=\"#\">Driving Directions</a></p>';
				//set content
				shape.setInfoContentHTML(infoBoxContent);
				shape.setIcon(myIcon);
				// enable line decluttering
				// disabled until ie fix	shape.setDeclutterMode(2);
				if(shape) map.addShape(shape);
			}
		}
		
		var rectLL = new MQA.RectLL(new MQA.LatLng(maxLat, minLng), new MQA.LatLng(minLat, maxLng));
		
		map.zoomToRect(rectLL);

    // at this point points are loaded on the map, close the location entry form
	if (SqueezeBox.open) {
	  SqueezeBox.close();
	}
	}
};


function constructSearchResult(searchResult){
	if(searchResult.shapePoints){
	
		if(searchResult.shapePoints.length == 2){
			var p = new MQA.Poi({lat:searchResult.shapePoints[0], lng:searchResult.shapePoints[1]});
			p.setRolloverContent(searchResult.name);
			p.setInfoTitleHTML(p.getRolloverContent());
			
			if(searchResult.poiImageUrl){
				var img = new Image();
				img.onload = function(){
					var icon = new MQA.Icon(this.src, this.height, this.width);
					p.setIcon(icon);
				}
				img.src = searchResult.poiImageUrl;

			}

			if(searchResult.fields){				
				var content = "";
				for(var obj in searchResult.fields){
					content += "<b>" + obj + "</b>" + ": " + searchResult.fields[obj] + "<br>";
				}					
				p.setInfoContentHTML(content);
			}
			else {
				p.setInfoContentHTML(' ');
			}
			
			return p;
		}
		else if(searchResult.shapePoints.length > 2){
			if(searchResult.shapePoints[0]  == searchResult.shapePoints[searchResult.shapePoints.length-2]
				&& searchResult.shapePoints[1]  == searchResult.shapePoints[searchResult.shapePoints.length-1]){
				var polygon = new MQA.PolygonOverlay();
				polygon.shapePoints = searchResult.shapePoints;
				polygon.color = "#e00000";
				polygon.colorAlpha = .8;
				polygon.fillColorAlpha = .4;
				polygon.fillColor = "#e00000";
				return polygon;
			}
			else {
				var line = new MQA.LineOverlay();
				line.shapePoints = searchResult.shapePoints;
				line.color = "#00e000";
				return line;
			}
		}
	}
	return null;
};

function decompress(results) {
	if(!results)
		return results;
		
	else if(!results.options)
		return results;
		
	else if(!results.options.shapeFormat)
		return results;	
	
    else if(!(results.options.shapeFormat=='cmp' || results.options.shapeFormat=='cmp6'))
		return results;
		
	var encoded;	
	if(results.polygon){	
		encoded = results.polygon;		
		results.polygon = decompressPoint(encoded, results.options.shapeFormat);
	}
	
	if(results.line){	
		encoded = results.line;		
		results.line = decompressPoint(encoded, results.options.shapeFormat);
	}
		
	if(results.searchResults){
		for(var i = 0; i < results.searchResults.length; i++){		
			encoded = results.searchResults[i].shapePoints;
			if(encoded){
				results.searchResults[i].shapePoints = decompressPoint(encoded, results.options.shapeFormat);
			}
		}
	}	

    return results;
};
  
function decompressPoint(encoded, shapeFormat) {

      var len = encoded.length, index=0,lat=0,lng = 0, array = [];
      try{
        while (index < len) {
          var b, shift = 0, result = 0;
          do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
          } while (b >= 0x20);
          var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
          
          lat += dlat;
          shift = 0;
          result = 0;
          do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
          } while (b >= 0x20);
            var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
  
          lng += dlng;
          if(shapeFormat=='cmp'){
            array.push(lat * 1e-5);
            array.push(lng * 1e-5);
          }else{
            array.push(lat * 1e-6);
            array.push(lng * 1e-6);
          }
        }
      } catch(ex) {
		alert(ex);
	  
      //error in encoding.
      }
	  
    return array;
};

// used to print object data / debugging
function dumpProps(obj) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else 
	  { var msg = i.name + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { 
		 dumpProps(obj[i], i); 
		 }
      }
   }
}


function renderecsStoreSearchResults(response) {
    var html = '';
    var i = 0;
    var j = 0;
    /* setting to ignore or handle ambiguities */	
    if (response.collections) { // Location ambiguities!
	    if (SqueezeBox.open) {
	  $('search_animation').setStyle('display', 'none');
    // SqueezeBox.resize({x:300, y:200}, false);
	}
    // Show list of suggested locations
        html = "<p>Whoops!  More than one location matches your search. Please select a location:</p><ol>";
        for (i = 0; i < response.collections.length; i++) {
           var collection = response.collections[i];
            for (j = 0; j < collection.length; j++) {
                html += '<li><a href=\"#\" class=\"ambiguous_address\" id=\"ambiguous_location_'+ j +'\" onclick=\"doChosenLocation(\'ambiguous_location_'+j+'\'); return false\">';
                html += '' + (collection[j].adminArea5 || ' ');  
                html += ' ' + (collection[j].adminArea4 || ' ');  
                html += ' ' + (collection[j].adminArea3 || ' ');  
                html += ' ' + (collection[j].adminArea2 || ' ');  
                html += ' ' + (collection[j].adminArea1 || '');  
                html += '</a></li>';
            }
        }
        html += '</ol>';
       
	   // resize overlay to fit results
       var newHeight = (200 + (25 * j));
	   SqueezeBox.resize({x:300, y:newHeight}, false);
	   
	   var ambiguousResults = document.getElementById('ambiguous_results');
       ambiguousResults.innerHTML = html;
  	   // set form to visible 
       // $('store_search_form').setStyle('display', 'block'); //The width is now 300px.
	   //addAmbiguousHandler();
        return;        
    }  
    // if (response.info.statuscode && (response.info.statuscode != 0) && (response.info.statuscode != 610)) {
    if (response.info.statuscode && (response.info.statuscode != 0)) {
        var text = "Whoops!  There was an error during the request";
		text += " [" + response.info.statuscode + "]:\n";
        if (response.info.messages) {
            for (i = 0; i < response.info.messages.length; i++) {
                text += response.info.messages[i] + "\n";
            }
        }
        alert(text);
	//	dumpProps(response.collections);
		return;
    }
    	
	if (response.resultsCount < 1) {
		alert("No results were in the search area");
        // close the search
        //SqueezeBox.close();
        // re-open the search form
		get_zipcode(false);
		return;
	}

	if(response.searchResults){
//	  $('storeResultTable').empty();
      // build the table to contain the result data

	  var storeSearchResultsTable = new HtmlTable($('storeResultTable'), {
          properties: {
             border: 0,
			 cellspacing: 0,
			 cellpadding: 0
          },
		   headers: ['', 'Store', 'Address', 'Phone'],
          /*rows: [
           ['apple', 'red'],
           ['lemon', 'yellow']
          ],*/
          zebra: true
       });
	  storeSearchResultsTable.empty();
	  // iterate over results and push them into the table
	  for(var i =0; i < response.searchResults.length; i++){
			var result = response.searchResults[i]
			ecsData = result.fields;
//			html += "<div class=\"store-listing\">";
//			html += 
            // build row
			var currentResultRow =  Array();
			currentResultRow.push('<div class=\"ecs-icon\"><img src=\"http://www.epicureancs.com/images/icons/ecsmapicon.png\" alt=\"Epicurean Pointer\"</div>');
//			currentResultRow.push('<div class=\"result-number\">' + result.resultNumber + '</div>');
			if(result.fields){
			  currentResultRow.push('<div class=\"store-name\">'+ ecsData.StoreName +'</div><!-- end store-name -->');
			  currentResultRow.push('<div class=\"store-address\">'+ ecsData.Address +'<br />'+ ecsData.City +', '+ ecsData.State +' '+ ecsData.Postal +'</div><!-- end store-name -->');
              if(ecsData.phone){
				  currentResultRow.push('<div class=\"store-phone\">'+ ecsData.phone +'</div><!-- end store-name -->');
				  }
		      else {
  			      currentResultRow.push('<div class=\"store-phone\">&nbsp;</div><!-- end store-name -->');
			  }

//			  currentResultRow.push('<div class=\"store-city\">'+ ecsData.City +'</div><!-- end store-name -->');
//			  currentResultRow.push('<div class=\"store-state\">'+ ecsData.State +'</div><!-- end store-name -->');
//			  currentResultRow.push('<div class=\"store-postal\">'+ ecsData.Postal +'</div><!-- end store-name -->');			  
			  }
			// put ron into table
			storeSearchResultsTable.push(currentResultRow);

//			html += "<div class=\"result-number\">" + result.resultNumber + "</div>";
//            ecsData = result.fields;
			// find out what we got
			// dumpProps(ecsData);
		//	if(result.fields){
		//		html += "<div class=\"store-name\">"+ ecsData.StoreName +"</div><!-- end store-name -->";
		//	}		
	//		html += "</div> <!-- end store-listing -->";
		  } // end for each result



 /*       html += '<div id=\"ecs-store-search-result-list\">';
		html += '<h1>Search Results</h1>';
		  for(var i =0; i < response.searchResults.length; i++){
			var result = response.searchResults[i]
			html += "<div class=\"store-listing\">";
			html += '<div class=\"ecs-icon\"><img src=\"http://www.epicureancs.com/images/icons/ecsmapicon.png\" alt=\"Epicurean Pointer\"</div>';
			html += "<div class=\"result-number\">" + result.resultNumber + "</div>";
            ecsData = result.fields;
			// find out what we got
			// dumpProps(ecsData);
			if(result.fields){
				html += "<div class=\"store-name\">"+ ecsData.StoreName +"</div><!-- end store-name -->";
			}		
			html += "</div> <!-- end store-listing -->";
		  }
		html += '</div><!-- end search results -->';*/
	}
    
	var divMap = document.getElementById("ecsStoreMap");
	divMap.innerHTML = "";
	if(divMap){
		window.mapExampleOne = new MQA.TileMap(divMap);
		//give zoom control
		MQA.withModule('zoomcontrol3', 'viewcontrol3', 'directions', 'shapes', 'route', function() {
			mapExampleOne.addControl(new MQA.LargeZoomControl3(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5, 5)));
			mapExampleOne.addControl(new MQA.ViewControl3(),new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT));
		});
    // dumpProps(response);
		processResults(response, window.mapExampleOne);
		divMap.style.display = "";
	}
	
	// inserte table object into page
//    $('storeResultTable').innerHTML = '';
	storeSearchResultsTable.inject($('ecsStoreSearchResults'));
	// empty table for next search
	
		
    //document.getElementById('ecsStoreSearchResults').innerHTML = html;
}

function doChosenLocation(selectedLocation){
  var locationToSearch = document.getElementById(selectedLocation).innerHTML; 
  document.getElementById('e1_origin').value = locationToSearch;
  doEcsSearch();
}

/* main search function */
function doEcsSearch() {
    // show a loading animation possibly
    if (SqueezeBox.open) {
	  
      //SqueezeBox.resize({x:300, y:175}, false); 	  
	  // show leading animation and resize box to fit
	  $('search_animation').setStyle('display', '');
  	  
      // hide form elements
	  $('search-input-container').setStyle('display', 'none');
	  $('radius-title').setStyle('display', 'none');
	  $('radius-selection').setStyle('display', 'none');

	}
	// clear result table
//	$('storeResultTable').empty();
	searchType = '';
   // document.getElementById('ecsStoreSearchResults').innerHTML = 'Pending...';    
    var script = document.createElement('script');
    script.type = 'text/javascript';
    showEcsSearchURL();
    var newURL = queryUrl.replace('YOUR_KEY_HERE', APP_KEY);
	newURL = newURL.replace("outFormat=xml", "outFormat=json");
    script.src = newURL;
    document.body.appendChild(script);
  };

/*
 * End Mapquest functions
 */

/*
 * Begin ECS mootools functionality
 */  
window.addEvent("domready", function() {
        showInitialMap();
		top.currentPage = "stores.php";
		get_zipcode(false);
		var searchButton = $('new_search_button_img');
		// get image
		var src = searchButton.getProperty('src');
		// get file name
		var extension = src.substring(src.lastIndexOf('.'),src.length);
		searchButton.addEvent('mouseenter', function(){
		  searchButton.setProperty('src',src.replace(extension,'_over' + extension));
		});
		searchButton.addEvent('mouseleave', function(){
		  searchButton.setProperty('src',src);
		});		
	});
	
function get_zipcode(retry)	{
	    // edited to load test popup instead of live for development
		var url = "http://www.epicureancs.com/zipcodePopup.php";
		var height = 150;
		if (retry) {
			url = url+"?retry";
			height = 500;
		}
        SqueezeBox.open(url, {
		    handler: 'ajax',
			evalScripts:true,
			size:{x:300,y:height},
            onUpdate: function () {
			  $('zip_form').addEvent('submit', function(event){
					event.preventDefault();
					if ($("e1_origin").value == "") {
						SqueezeBox.close();
					}
					else {
				        doEcsSearch();
				        // SqueezeBox.close();
					}
				});
			},
			onComplete: function () { this.evalScripts();},
			onClose: function () {			
			  /*var newSearchElement = $('location_search_button');
			  newSearchElement.fade('in');*/
              /* var slideVarC = new Fx.Slide(slideElementC, {
				//Fx.Slide Options
				mode: 'vertical', //default is 'vertical'
				//wrapper: this.element, //default is this.element
		 
				//Fx Options
				//link: 'cancel',
				transition: 'sine:in',
				duration: 300
		    });*/
  			// show location search button...
            // var searchAgain = '<div class=\"location_search_button\"><a class="new_search_button" href=\"#\" onclick="get_zipcode(); return false;"><img src=\"http://test.epicureancs.com/images/buttons/map_footer_button.gif\" alt=\"New Search\" /></a></div>';
			// document.getElementById('ecsStoreSearchResults').innerHTML = searchAgain;
            // myVerticalSlide.innerHTML = searchAgain;
            // myVerticalSlide.slideIn()
			}
		});
	}
	
// set e1_radius to regenerate query with selected radius
function updateRadiusSelection(ecsRadius) {
  $('e1_radius').set('value', ecsRadius);
}
	
/* End mapquest search and map functions */
	
	
// un-implemented direction code below here
// Direction / routing -- disabled for now
/*
var SAMPLE_DIRECTION_POST = HOST_URL + '/directions/v1/route?key=YOUR_KEY_HERE&from=ORIGIN_LOCATION&to=DESTINATION_LOCATION&callback=renderNarrative';
// var SAMPLE_DIRECTION_POST = HOST_URL + '/directions/v1/route?key=YOUR_KEY_HERE&from=47.0961,-91.6659&to=55419&callback=renderNarrative';
function showBasicURL() {
    var safe = SAMPLE_DIRECTION_POST;
	// replace origin and destination with our data
    document.getElementById('basicSampleUrl').innerHTML = safe.replace(/</g, '&lt;').replace(/>/g, '&gt;');
};
*/

/* Direction tests - commented out for now*/
/*
function doClick(origin_location, destination_location) {
	document.getElementById('narrative').innerHTML = 'Pending...';
    var script = document.createElement('script');
    script.type = 'text/javascript';
    showBasicURL();
    var newBaseURL = SAMPLE_DIRECTION_POST.replace('YOUR_KEY_HERE', APP_KEY);
	var newURLWithOrigin = newBaseURL.replace('ORIGIN_LOCATION', origin_location);
	var newURL = newURLWithOrigin.replace('DESTINATION_LOCATION', destination_location);
	//alert(newURL);
    script.src = newURL;
    document.body.appendChild(script);
};
*/
/* Directions - commented out for now */
/*
function renderNarrative(response) {
    var legs = response.route.legs;
    var html = '';
    var i = 0;
    var j = 0;
    var trek;
    var maneuver;
    
    html += '<table><tr><th colspan=3>Narrative</th></tr><tbody>'
    
    for (; i < legs.length; i++) {
        for (j = 0; j < legs[i].maneuvers.length; j++) {
            maneuver = legs[i].maneuvers[j];
            
            html += '<tr>';
            html += '<td>&nbsp;';
            if (maneuver.iconUrl) {
                html += '<img src="' + maneuver.iconUrl + '">  '; 
            } 
            for (k = 0; k < maneuver.signs.length; k++) {
                var sign = maneuver.signs[k];
                if (sign && sign.url) {
                    html += '<img src="' + sign.url + '">  '; 
                }
            }
            
            html += '</td>'
            html += '<td>' + maneuver.narrative + '</td>'
            html += '<td>'
            if (maneuver.mapUrl) {
                html += '<img src="' + maneuver.mapUrl + '">';
            } else {
                html += '&nbsp;'
            }
            html += '</td>'
            html += '</tr>';
        }
    }
    
    html += '</tbody></table>';
    
    document.getElementById('narrative').style.display = "";
    document.getElementById('narrative').innerHTML = html;
}

*/
/* Directions */
/*
function getDirections(origin_location, destination_location) {
//  alert('Take a right');
  var currentMap = window.mapExampleOne;
 // alert(currentMap);
  doClick(origin_location, destination_location);
/*  currentMap.addRoute([
    {postalCode: '56304'},
    {city: 'Steamboat Springs', state: 'CO'}
  ]);*/
  

  
/* window.mapExampleOne = new MQA.TileMap(
    document.getElementById('mapExampleOne'),
    7,
    {lat:39.743943, lng:-105.020089}, 
    'mapExampleOne');

    alert('map loaded?');
 
	MQA.withModule('directions', function() {
			mapExampleOne.addRoute([
					{latLng: {lat: 39.637433, lng: -105.163867}},
					{city: 'Silverthorn', state: 'CO'},
					{city: 'Kremmling', state: 'CO'},
					{city: 'Steamboat Springs', state: 'CO'}
				]
				/*, 
				{ribbonOptions:{draggable:true, draggablepoi:true}},
				displayNarrative*/
	/*			);
	});*/
 /* currentMap.addRoute([
    {latLng: {lat: 39.637433, lng: -105.163867}},
    {latLng: {lat: 39.743943, lng: -105.020089}}
  ]);*/

 
  //Uses the MQA.TileMap.addRoute function (added to the TileMap with the directions module)
  //passing in an array of location objects as the only parameter.
/*  currentMap.addRoute([
    {postalCode: '55616'},
    {postalCode: '55419'}
  ]);*/
/*    window.map = new MQA.TileMap(
    document.getElementById('ecsStoreMap'),
    7,
    {lat:39.743943, lng:-105.020089}, 
    'map');

	MQA.withModule('directions', function() {
			currentMap.addRoute([
					{latLng: {lat: 39.637433, lng: -105.163867}},
					{city: 'Silverthorn', state: 'CO'},
					{city: 'Kremmling', state: 'CO'},
					{city: 'Steamboat Springs', state: 'CO'}
				]
				/*, 
				{ribbonOptions:{draggable:true, draggablepoi:true}},
				displayNarrative
				);
	});*/
  
// clear map and show route?
/*  	var divMap = document.getElementById("ecsStoreMap");
	divMap.innerHTML = "";
	if(divMap){
		window.mapExampleOne = new MQA.TileMap(divMap);
		//give zoom control
		MQA.withModule('zoomcontrol3', 'viewcontrol3', 'directions', 'shapes', function() {
			mapExampleOne.addControl(new MQA.LargeZoomControl3(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5, 5)));
			mapExampleOne.addControl(new MQA.ViewControl3(),new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT));
  		    mapExampleOne.addRoute([
				{latLng: {lat: 39.637433, lng: -105.163867}},
				{latLng: {lat: 39.743943, lng: -105.020089}}
          ]);
		});
    // dumpProps(response);
	//	processResults(response, window.mapExampleOne);
		divMap.style.display = "";
	 }*/
//	 MQA.withModule('directions', function() {

  //Uses the MQA.TileMap.addRoute function (added to the TileMap with the directions module) 
  //passing in an array of location objects as the only parameter.
//  mapExampleOne.addRoute([
 //   {latLng: {lat: 39.637433, lng: -105.163867}},
  //  {latLng: {lat: 39.743943, lng: -105.020089}}
 // ]);

//});

    //http://www.mapquestapi.com/directions/v1/route?key=YOUR_KEY_HERE&from=Lancaster,PA&to=York,PA&callback=renderNarrative\">Driving Directions
/* function cloning curly brace } */ 
/* End direction functionality */