/* global "gateway" for popup to parent communication */
function getRouteData(){
        var routeAsString = "";
        routeAsString = dojo.toJson(c._routeDetailsForPrint);
        return routeAsString;
}

dojo11.require("dojox.fx");
dojo11.declare("MQResultsController", null, {
	constructor: function() {
		this._wireUpFormForEnterTrap();
		this._geoCodeDestAddress();
		this._showMap();		
  },
  
  	_currentStoreAddr: null,
	_currentStoreAddr2: null,
	_geoAddressForDest:null,
  
  _wireUpFormForEnterTrap: function(){
       if(dojo.isFF){
           dojo11.connect(dojo11.byId('storeLookupForm'), "onsubmit", this, "_showMap");
       }else{
           dojo11.query('#storeLookupForm input').forEach(function(item){
             dojo.connect(item, "onkeypress", null, function(evt){
               if(evt.keyCode == 13){
                   c._showMap(evt);
               }
             });
           });
           dojo11.connect(dojo11.byId('storeLookupForm'), "onsubmit", this, "_showMap");
       }                
   },
        
  	_populateAddress: function(){
  		var path = window.location.pathname;
  		var start = path.lastIndexOf("stores");
  		var stop  = path.indexOf("/storelocator");
  		var storesPath = path.substring(start,stop).toString();
  		var store = storesPath.substring(7);
  		
  		var sname,street,cty,state,zip,phone;
  		sname = store+"-name";
  		street = store+"-street";
  		cty = store+"-city";
  		state = store+"-state";
  		zip = store+"-postalCode";
  		phone=store+"-phone";
  		
		_currentStoreAddr = new DataManagerRecord();
		_currentStoreAddr.setStoreName(dojo.byId(sname).innerHTML);
		_currentStoreAddr.setStreet(dojo.byId(street).innerHTML);
		_currentStoreAddr.setCity(dojo.byId(cty).innerHTML);
		_currentStoreAddr.setState(dojo.byId(state).innerHTML);
		_currentStoreAddr.setPostalCode(dojo.byId(zip).innerHTML);
		_currentStoreAddr.setPhone(dojo.byId(phone).innerHTML); 
		_currentStoreAddr.setCountry("USA");
		
		//address for geocoding
		_currentStoreAddr2 = new MQAddress();
		_currentStoreAddr2.setStreet(dojo.byId(street).innerHTML);
		_currentStoreAddr2.setCity(dojo.byId(cty).innerHTML);
		_currentStoreAddr2.setState(dojo.byId(state).innerHTML);
		_currentStoreAddr2.setPostalCode(dojo.byId(zip).innerHTML);
		_currentStoreAddr2.setCountry("USA");
		return _currentStoreAddr2;
	},
  
  _geoCodeDestAddress:function(){
		this._geoAddressForDest = this._getGeoCode(this._populateAddress());
  },
  
  _showMap:function(event){
  	if(event != null){
  		event.preventDefault();
  		var isValid = this._showDrivingDirections();
  		if(!isValid){
  			event.preventDefault();
  		}else{
  			return false;
  		}
  	}else{
  		this._showDrivingDirections();
  	}
  },
  
  _getGeoCode: function(addr){
		var location;
		var locationcollection = new MQLocationCollection("MQGeoAddess");
		var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		
		//Geocode address
		geoExec.geocode(addr,locationcollection);
	   
	    if(locationcollection.getSize()==0){
			//If results are 0 then the address can not be geocoded.
			this._showErrorMessage("The address you specified seems to be incorrect. Please enter a valid address below.");
			return false;
	    }
	    else if(locationcollection.getSize()==1){
			//If a single result is returned from the geocoder, validate the result, return the geocoded address
			var location = locationcollection.getAt(0);
			if(validateResultCode(location.getResultCode())){
				location = locationcollection.get(0);
			}
			else {
				this._showErrorMessage("The address you specified seems to be incorrect. Please enter a valid address below.");
				return false;
			}
		}
		else {
			  this._showErrorMessage("The address you specified seems to match multiple addresses.  Please enter a more specific address, or try a city and state or zip code only.");
			  return false;
		}
		return location;
   },
  

   _showDrivingDirections: function(){
	  var geoAddress, name, city, state, country, zipcode, miles;
	  var locationcollection=new MQLocationCollection();
	  var addr = new MQAddress();
	  addr.setStreet(dojo.byId("a0").value);
	  addr.setCity(dojo.byId("c0").value);
	  var state=dojo.byId("s0");
	  addr.setState(state.options[state.selectedIndex].value);
	  addr.setPostalCode(dojo.byId("z0").value);
	  addr.setCountry(dojo.byId("u0").value);
	  var zipCode=dojo11.trim(dojo.byId('z0').value);
	  var country=dojo.byId("u0");
	  city=dojo.byId("c0").value;
	  var selCountry=country.options[country.selectedIndex].value
	  var stateValue=state.options[state.selectedIndex].value;
	  
	  if(city=="" && stateValue=="" && zipCode==""){
				this._showErrorMessage("Please enter a valid City and State or Zip Code to continue.");
				return false;
	  }
		
	  if (((city != "" && stateValue=="") ||
   	     (city == "" && stateValue != "")) &&  zipCode == "") {
			this._showErrorMessage("Please enter a valid City and State or Zip Code to continue.");
			return false;
	  }
		
	  if(zipCode != "" && stateValue!= ""  && selCountry != "CA" && !ValidZip(zipCode)){
			this._showErrorMessage("The state and zip code do not match. Please make sure they are correct.");
			return false;
	  }
	  //Geocode MQAddress
	  var geoAddressForOrigin = this._getGeoCode(addr);
	 

	  if(geoAddressForOrigin){
		 //If geocoded successfully perform route
		  this._route(geoAddressForOrigin,this._geoAddressForDest);
	  }else{
	  	return false;
	  } 
	       
   },
   
  	/**
	* Function to perform route
	* 
	*/
	_route:function(geoAddressForOrigin,geoAddressForDest){
		var tempCollection = new MQPoiCollection();
		var mapInit = new MQMapInit();
		var destGeoAddress, origGeoAddress;
		origGeoAddress = geoAddressForOrigin;
		destGeoAddress = geoAddressForDest;
		
		//Build Map Div
		dojo11.byId('mapDiv').innerHTML="";
		var mapwindow = dojo11.byId('mapDiv');

		//Create Destination Icon
		var endIcon = new MQMapIcon();
		var endImg = _globalContentImagesPath.replace (/1.gif/, 'Finish_Icon.gif');
		endIcon.setImage(endImg, 23, 23, true, false);

		//Create Origin Icon
		var startIcon = new MQMapIcon();
		var startImg = _globalContentImagesPath.replace (/1.gif/, 'Start_Icon.gif');
		startIcon.setImage(startImg, 23, 23, true, false);

		//Create Origin Poi and add to the Map
		var startPoi = new MQPoi(origGeoAddress.getMQLatLng(), startIcon);
		startPoi.setInfoTitleHTML("Origin");
		startPoi.setInfoContentHTML(mqAddressToString(origGeoAddress));
		tempCollection.add(startPoi);

		//Create Destination Poi and add to the Map
		var endPoi = new MQPoi(destGeoAddress.getMQLatLng(), endIcon);
		endPoi.setInfoTitleHTML("Destination");
		endPoi.setInfoContentHTML(mqAddressToString(destGeoAddress));
		tempCollection.add(endPoi);
		
		mapInit.setBestFitRect( tempCollection.getBoundingRect() );
		
		//Create TileMap
		wsMap = new MQTileMap(mapwindow, 7,null,"map", mapInit);
		wsMap.addPois(tempCollection);

		//Add zoom controls to Map
		var zoomControl =  new MQLargeZoomControl();
		wsMap.addControl(zoomControl, new MQMapCornerPlacement(MQMapCorner.TOP_LEFT, new MQSize(0, 0)))

		//Add view controls to map
		wsMap.addControl(new MQNoAerialViewControl(wsMap), new MQMapCornerPlacement(MQMapCorner.TOP_RIGHT, new MQSize(-4, 0)));

		//Place MapQuest and Copyright logos
		wsMap.setLogoPlacement(MQMapLogo.MAPQUEST, new MQMapCornerPlacement(MQMapCorner.TOP_LEFT, new MQSize(44, 0)));
		wsMap.setLogoPlacement(MQMapLogo.SCALES, new MQMapCornerPlacement(MQMapCorner.BOTTOM_LEFT, new MQSize(50, 0)));
		wsMap.setLogoPlacement(MQMapLogo.NAVTEQ_COPYRIGHT, new MQMapCornerPlacement(MQMapCorner.BOTTOM_LEFT, new MQSize(208, 0)));
		wsMap.setLogoPlacement(MQMapLogo.MAPQUEST_COPYRIGHT, new MQMapCornerPlacement(MQMapCorner.BOTTOM_RIGHT, new MQSize(0, 0)));
		wsMap.setLogoPlacement(MQMapLogo.ICUBED_COPYRIGHT, new MQMapCornerPlacement(MQMapCorner.BOTTOM_RIGHT, new MQSize(103, 1)));

		//Setup Route Exec object
		var routeExec = new MQExec(routeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		var session = new MQSession();
		var routeRes = new MQRouteResults();
		var wayPoints = new MQLocationCollection();
		var myBB = new MQRectLL(new MQLatLng(),new MQLatLng());

		//Add Origin and Destination to MQLocationCollection
		wayPoints.add(origGeoAddress);
		wayPoints.add(destGeoAddress);

		//Set any Route Options
		var routeOpt = new MQRouteOptions();
		routeOpt.setMaxShapePointsPerManeuver(MAX_SHAPE_POINTS);

		//Create Session for route
		var sessId = routeExec.createSessionEx(session);
		//Do Route
		routeExec.doRoute(wayPoints,routeOpt,routeRes,sessId,myBB);

		//Add route highlight to map
		wsMap.addRouteHighlight(myBB,"http://map.access.mapquest.com",sessId,true);

		//Perform Best Fit on the Map
		//wsMap.bestFit(false, 1, 11);
                
        //wire map event handlers
        MQEventManager.addListener(wsMap,"zoomend", this._handleZoomend);
		MQEventManager.addListener(wsMap,"dragend", this._handleDragend);
		//Display Results Table
		this._showRouteResults(routeRes, origGeoAddress, destGeoAddress);
	},
	
	_showRouteResults:function(routeResults, origAddress, destAddress){
                dojo11.byId('divResults').innerHTML = "";
                this._routeDetailsForPrint = {};
                
                var div = document.createElement('div');
                div.setAttribute('id', 'from-estimate');
                
                var start = "";
                if(routeResults.getLocations().getAt(0).getStreet() != "")
                        start = routeResults.getLocations().getAt(0).getStreet() + "<br />";

                this._routeDetailsForPrint["start"] = {};
                this._routeDetailsForPrint["start"]["street"] = routeResults.getLocations().getAt(0).getStreet();
                this._routeDetailsForPrint["start"]["city"] = routeResults.getLocations().getAt(0).getCity();
                this._routeDetailsForPrint["start"]["state"] = routeResults.getLocations().getAt(0).getState();
                this._routeDetailsForPrint["start"]["postalCode"] = routeResults.getLocations().getAt(0).getPostalCode();
                this._routeDetailsForPrint["start"]["country"] = routeResults.getLocations().getAt(0).getCountry();
                
                start += routeResults.getLocations().getAt(0).getCity() + ", " + routeResults.getLocations().getAt(0).getState() + " " + routeResults.getLocations().getAt(0).getPostalCode();
                this._routeDetailsForPrint["startSummary"] = start;
                
                var totalDistance = routeResults.getTrekRoutes().get(0).getDistance().toString();
                totalDistance = totalDistance.substring(0, totalDistance.indexOf('.') + 3) + " miles";
                this._routeDetailsForPrint["totalDistance"] = totalDistance;
                
                var totalTime = routeResults.getTrekRoutes().get(0).getTime();
                if(totalTime > 3600)
                        totalTime = formatTime(totalTime, "%h hrs %m minutes");
                else
                        totalTime = formatTime(totalTime , "%m minutes");
                this._routeDetailsForPrint["totalTime"] = totalTime;
                        
                div.innerHTML = "<label>From:</label><p>" + start + "</p>";
                dojo11.byId('divResults').appendChild(div);
                
                div = document.createElement('div');
                div.setAttribute('id', 'to-estimate');
                
                var destination = "";
                if(routeResults.getLocations().getAt(1).getStreet() != "")
                        destination = routeResults.getLocations().getAt(1).getStreet() + "<br />";
                
                this._routeDetailsForPrint["destination"] = {};
                this._routeDetailsForPrint["destination"]["street"] = routeResults.getLocations().getAt(1).getStreet();
                this._routeDetailsForPrint["destination"]["city"] = routeResults.getLocations().getAt(1).getCity();
                this._routeDetailsForPrint["destination"]["state"] = routeResults.getLocations().getAt(1).getState();
                this._routeDetailsForPrint["destination"]["postalCode"] = routeResults.getLocations().getAt(1).getPostalCode();
                this._routeDetailsForPrint["destination"]["country"] = routeResults.getLocations().getAt(1).getCountry();
                
                destination += routeResults.getLocations().getAt(1).getCity() + ", " + routeResults.getLocations().getAt(1).getState() + " " + routeResults.getLocations().getAt(1).getPostalCode();
                this._routeDetailsForPrint["destinationSummary"] = destination;
                div.innerHTML = "<label>To:</label><p>" + destination + "</p>";
                dojo11.byId('divResults').appendChild(div);
                
                
                var divDirectons = document.createElement('div');
                divDirectons.setAttribute('id', 'directions');
                
                var table = document.createElement("table");
                //cellspacing="0" summary="Driving directions to Pottery Barn" id="driving-steps"
                table.setAttribute('cellSpacing', '0');
                table.setAttribute('summary', 'Driving directions to Pottery Barn');
                table.id = 'driving-steps';
                
                var tBody = document.createElement('tbody');
                var tr = document.createElement('tr');
                var th = document.createElement('th');
                th.setAttribute('abbr', 'Driving Directions');
                th.setAttribute('scope', 'col');
                th.innerHTML = "Driving Directions";
                tr.appendChild(th);
                
                th = document.createElement('th');
                th.setAttribute('abbr', 'Distance');
                th.setAttribute('scope', 'col');
                th.innerHTML = "Distance";
                tr.appendChild(th);
                
                th = document.createElement('th');
                th.setAttribute('abbr', 'Time');
                th.setAttribute('scope', 'col');
                th.innerHTML = "Time";
                tr.appendChild(th);
                
                tBody.appendChild(tr);
                
                tr = document.createElement('tr');
                
                var narrative = "";
                this._routeDetailsForPrint["directions"] = [];
                var distance, time = -1;
                
                //routeResults.getTrekRoutes().get(0).getManeuvers().get(0).getNarrative()
                for(var i = 0; i < routeResults.getTrekRoutes().get(0).getManeuvers().getSize(); i++){
                        narrative = routeResults.getTrekRoutes().get(0).getManeuvers().get(i).getNarrative();
                        tr = document.createElement('tr');
                        if(i % 2 == 1)
                                tr.className =  'alt';
                        td = document.createElement('td');
                        td.innerHTML = (i+1) + ". " + narrative;
                        tr.appendChild(td);
                        
                        distance = routeResults.getTrekRoutes().get(0).getManeuvers().get(i).getDistance();
                        td = document.createElement('td');
                        distance = distance.substring(0, distance.indexOf('.') + 3) + " miles";
                        td.innerHTML = distance;
                        tr.appendChild(td);
                        
                        time = routeResults.getTrekRoutes().get(0).getManeuvers().get(i).getTime();
                        td = document.createElement('td');
                        if(time > 3600)
                                time = formatTime(time, "%h hrs %m mins");
                        else
                                time = formatTime(time , "%m mins");
                        td.innerHTML = time;
                        tr.appendChild(td);
                        
                        tBody.appendChild(tr);
                        
                        this._routeDetailsForPrint["directions"][i] = {"narrative": narrative, "distance": distance, "time": time};
                }
                
                tr = document.createElement('tr');
                td = document.createElement('td');
                td.innerHTML = "<strong>Total Distance:</strong> " + totalDistance + "    <strong>Estimated Time: </strong>"+totalTime;
                tr.appendChild(td);
                tBody.appendChild(tr);
                                
                table.appendChild(tBody);
                divDirectons.appendChild(table);
                dojo11.byId('divResults').appendChild(divDirectons);
                
               // this._teardownMapTransition();
	},
 	
   _showErrorMessage: function(errorMessage){
                dojo11.byId('errorDisplay').style['display'] = 'block';
                dojo11.byId('errorDisplay').style['opacity'] = '0';
                dojo11.byId('errorHook').innerHTML = errorMessage;
                var anim = dojo11.fadeIn({ node: dojo11.byId('errorDisplay'), duration: 500 }).play();
                dojo11.connect(anim, "onEnd", null, function(){
                        dojo11.byId('errorDisplay').style['opacity'] = '1.0';
                });
   },
   _hideErrorMessage: function(){
                dojo11.byId('errorHook').innerHTML = '';
                dojo11.byId('errorDisplay').style['display'] = 'none';
   },
   
   _callCoreMetrics: function(elementId){
                cmCreatePageElementTag(elementId, "Store Locator");
   },
   
   _callCoreMetricsWithPageId: function(pageId){
                cmCreateManualPageviewTag(pageId, "Store Locator" );
   },
   
   handleMapViewTypeChangeEvent: function(mapType){
                var temp = mapType + " map";
                this._callCoreMetrics(temp);
   },
   
   _handleZoomend: function(evt){
                c._callCoreMetrics("Zoom");      
   },
   
   _handleDragend: function(evt){
                c._callCoreMetrics("Map Pan");            
    }

});