/**
 * JavaScript for the landing page, which displays the single WSH store on a map
 * @author Puran 
 * @Copyright WSH, 2008 
 */
dojo.require("dojox.fx");
dojo.declare("MQLandingController", null, {
	constructor: function() {		
		this._showMapWithStore();      
		this._wireUpFormForEnterTrap();
        dojo.connect(dojo.byId('storeLookupForm'), "onsubmit", this, "handleDrivingDirection");  
	},
	
	_currentStoreAddr: null,
	_currentStoreAddr2: null,
	
	_wireUpFormForEnterTrap: function(){
        if(dojo.isFF){
           dojo11.connect(dojo11.byId('storeLookupForm'), "onsubmit", this, "handleDrivingDirection");
        }else{
           dojo11.query('#storeLookupForm input').forEach(function(item){
              dojo.connect(item, "onkeypress", null, function(evt){
               if(evt.keyCode == 13){
                 c.handleDrivingDirection(evt);
               }
              });
           });
        }                
    },
    
    handleDrivingDirection: function(evt){
		var isFormValid = this._isFormValid();
		if(!isFormValid){
			evt.preventDefault();
		}else{
			dojo11.byId('storeLookupForm').submit();
			return false;
		}
	},
	
	_isFormValid: function(){
		if( this._validateAddress()){
			return true
		}
		else{
		 return false;
		}
	 },
	 
	 //have to call to mapquest for address validation.. though this might make things slower.
	_validateAddress: function(){
		var addr, geoAddress, name, city, state, country, zipcode, miles;
		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;
		}
		var locationcollection = new MQLocationCollection();
		var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		//Geocode address
		geoExec.geocode(addr, locationcollection, null);
	
		if(locationcollection.getSize()==0){
			//If results are 0 then the address can not be geocoded.
			//this._showErrorMessage("Please enter the valid address");
			return true;
		}
		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())){
				return true;
			}
			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;
		}
	},
	
	_showErrorMessage: function(errorMessage){
        //errorDisplay
        dojo.byId('errorDisplay').style['display'] = 'block';
        dojo.byId('errorDisplay').style['opacity'] = '0';
        dojo.byId('errorHook').innerHTML = errorMessage;
        var anim = dojo.fadeIn({ node: dojo.byId('errorDisplay'), duration: 500 }).play();
        dojo.connect(anim, "onEnd", null, function(){
             dojo.byId('errorDisplay').style['opacity'] = '1.0';
        });
     },
    
    _hideErrorMessage: function(errorMessage){
        //errorDisplay
        var anim = dojo.fadeOut({ node: dojo.byId('errorDisplay'), duration: 500 }).play();
        dojo.connect(anim, "onEnd", null, function(){
        dojo.byId('errorHook').innerHTML = '';
             dojo.byId('errorDisplay').style['display'] = 'none';
        });
    },
	
	_populateAddress: function(){
		_currentStoreAddr = new DataManagerRecord();
		_currentStoreAddr.setStoreName(dojo.byId("storeName").innerHTML);
		_currentStoreAddr.setStreet(dojo.byId("street").innerHTML);
		_currentStoreAddr.setCity(dojo.byId("city").innerHTML);
		_currentStoreAddr.setState(dojo.byId("state").innerHTML);
		_currentStoreAddr.setPostalCode(dojo.byId("postalCode").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("city").innerHTML);
		_currentStoreAddr2.setState(dojo.byId("state").innerHTML);
		_currentStoreAddr2.setPostalCode(dojo.byId("postalCode").innerHTML);
		_currentStoreAddr2.setCountry("USA");
		return _currentStoreAddr2;
	},	
	
	/**
	 * Display the store on the map, use the defined address of store
	 * geocodes it and displays on the map. 
	 */
	_showMapWithStore: function(){
		var geoAddress = this._getGeoCode(this._populateAddress());
		
		//If this function has geocoded an address either by location
		//category then assign the latitude and longitude to the hidden form fields for those values.
		if(geoAddress){
			this._showMap(geoAddress);
		}
	},
	
	_getGeoCode: function(addr){
		var location;
		var locationcollection = new MQLocationCollection("MQGeoAddress");
		var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		
		//Geocode address
		geoExec.geocode(addr,locationcollection);
		
		if(locationcollection.getSize()>0){
			location = locationcollection.get(0);
		}
		
		return location;
	},
	
	
	_showMap:function(geoAddress){
		//Build Map Div
        dojo11.byId('mapDiv').innerHTML="";
                        
		var mapwindow = dojo11.byId('mapDiv');
		wsMap = new MQTileMap(mapwindow,null,null,"map",null);

		//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)));
		
		var storeLatLng = geoAddress.getMQLatLng();
		storeIcon    = new MQMapIcon();
		
		//in case we have any custom image we can uncomment these three lines to use that,
		//var currentImg = _globalContentImagesPath.replace (/1.gif/, (i+1) + '.gif');                     
		//icon.setImage(currentImg, 20, 20, true, false);
		//storeIcon.setImage();
		
		wsMap.removeAllPois();		
		var storePoint = new MQPoi(storeLatLng);
		storePoint.setIcon(storeIcon);
		storePoint.setInfoTitleHTML(_currentStoreAddr.getStoreName());
		storePoint.setInfoContentElement(this._getInfoContentElement());
		storePoint.setRolloverEnabled(true);
		storePoint.setKey(1);
				
		//wire POI event handlers
		//MQEventManager.addListener(storePoint,"mouseover", this._handlePOIOnMouseOver);
		//MQEventManager.addListener(storePoint,"click", this._handlePOIOnClick);
        //MQEventManager.addListener(storePoint,"close", this._handlePOIOnClose);
		
		wsMap.addPoi(storePoint);
		dojo.query(".copyright").forEach(function(item) { item.style["display"] = "block"; });
		dojo11.byId("mapDiv").style.visibility="visible";
    	wsMap.setCenter(storeLatLng,7);
		
	},
	
    _getInfoContentElement: function(){
		var htmlElement = document.createElement("div");
		htmlElement.appendChild(document.createTextNode(_currentStoreAddr.getStreet()));
		htmlElement.appendChild(document.createElement("br"));
		htmlElement.appendChild(document.createTextNode(_currentStoreAddr.getCity()+" "+_currentStoreAddr.getState()+","+_currentStoreAddr.getPostalCode()));
		htmlElement.appendChild(document.createElement("br"));
		htmlElement.appendChild(document.createTextNode("Phone: "+_currentStoreAddr.getPhone()));
		return htmlElement;
	},
	
	handleMapViewTypeChangeEvent: function(mapType){
                var temp = mapType + " map";
                this._callCoreMetrics(temp);
    },
    
    _callCoreMetrics: function(elementId){
                cmCreatePageElementTag(elementId, "Store Locator");
   }	
	
});