
/**
 * Search strategy:
 *   1. When user clicks on "SEARCH", we have a centerpoint.
 *   2. The search in java will search for X nearest stores (X is configurable, but say 10. 
 *      or to a distance of 50 km, whichever comes first.
 *   3. On return from the server, Javascript will display the stores found.
 *      If there is no stores found,  an error message is displayed.
 *   4. Pan and zoom: le center point reste.
 *        - si on pan, le rectangle est elargi
 *        - si on zoom out: le rectangle est elargi
 *        - si on zoom in: rien de change  
 */

  function LoadMap(prov)  
  {
	  try {
		  SLMap.GetInitialMap(prov); // create our map.
	  } catch (e) {
		  // this happens if Microsoft VE is down. It will likely throw "SLMap is not defined".
		  SLErr.ShowStoreLocatorUnavailableError("LoadMap(" + prov + ")", e);
	  }
  }

 
  
  /**
	 * Handler called when map is changed (panned, zoomed, searched) Allows to
	 * get the delLat * Long depending on the zoom level.
	 */
function mapChangeHandler(e) {

	/**
	 * Now that this handler has done its job of telling 
	 * us that the "where" search is complete..
	 *   1) unhook it
	 *   2) and do the "what" search search
	 *   
	 *   FYI: - "where" search is by VirtualEarth
	 *        - "what" search is our Ajax/Dwr search.
	 */
	
	// Unhook onchangeview handler
	SLMap.GetMap().DetachEvent("onchangeview", mapChangeHandler);

	// Then do our "what" search
	if (SLMap.isSearchActive()) {
		/**
		 * Flag that we have done the search!!
		 */
	    SLMap.DeactivateSearchFlag();

	    ajaxFindStoresFromCenter();
	}
}
  
  
/**
 * Show 'over' icon when mouseover the store in the Results tab. (the reverse is
 * UnderIcons where the regular icon is displayed on mouseout of the store in
 * Results tab).
 */
var hilitedStoreElem = null;

function OverIcons(shapeId, storeElemName) {
	
	SLBub.DeleteBub(null); // hide store bubble if any
    // If there was a hilgihted store, unhilight it first.
    if (hilitedStoreElem) {
    	hilitedStoreElem.className = "";
    }
    
    // hilight store element
    hilitedStoreElem = document.getElementById(storeElemName);
    hilitedStoreElem.className = "active";
			
    var shape = SLMap.GetMap().GetShapeByID(shapeId);
    if (shape) {
		var storeType = shape.Store.type;
		shape.SetCustomIcon(SLUtil.GetStoreHilightedIcon(storeType));
    }
}


function UnderIcons(shapeId, storeElemName){
    var shape = SLMap.GetMap().GetShapeByID(shapeId);
    if (shape) {
		var storeType = shape.Store.type;
		shape.SetCustomIcon(SLUtil.GetStoreRegularIcon(storeType));
    }
}

/**
 * This OnClick handler simply removes the Shape Control (aka the store bubble)
 */
function mapOnClickHandler(e) {
	var shape = null;
	
    if (e.elementID != null) {
		shape = SLMap.GetMap().GetShapeByID(e.elementID);
    }
    
    /*
     * If we click on a shape, then show its bubble
     * otherwise, hide bubble
     */
    if (shape && shape.Store) {
    	SLBub.AddBub(shape);
		storeLocator.icoClick(shape.StoreId);
    } else {
    	SLBub.DeleteBub(null);
    }
}


 /**
   * Handler so that when someone hovers over the map:  If a store pushpin
   * is hovered over, then:
   *  1. display the Results page that contains the corresponding store
   *  2. highlight it
   *  3. create the shape control (aka store info bubble).
   *  NOTE: You should NOT change the store pushpin in this handler!
   *        Doing that would confuse VE 
   *         
   */
var lastShapeOver = null;
function mapMouseOverHandler(e) {

    if (e.elementID != null){
		
		var shape = SLMap.GetMap().GetShapeByID(e.elementID);
		//SLUtil.debug(shape.Store.name + "-" + shape.Store.mall + " <-mouseIn at " + e.mapX + "&" + e.mapY);
		
		// put hilgiht icon
		/*
		shape.SetCustomIcon((shape.Store.type == 10 || shape.Store.type == 30)  ? 
                "/web/common/all_languages/all_regions/images/logos/bell_icon_over.gif" :
                "/web/common/all_languages/all_regions/images/logos/other_icon_over.gif ");
		*/
		
		SLBub.AddBub(shape);
		//storeLocator.icoClick(shape.StoreId);
	}
}

/**
 * Mouseout of the map.
 * @param e e can check if the mouseout was from a pushpin by using e.elementID.
 */
function mapMouseOutHandler(e) {

	/**
	 * Now we:
	 *    1. check if mouse is still in the bbox of the shape.
	 *       If it is, do nothing, else, reattach mouseOver, and delete shape.
	 */
    if (e.elementID != null) {
    	
		var shape = SLMap.GetMap().GetShapeByID(e.elementID);
		
		if (!shape) {
			shape = lastShapeOver;
		}		
	}
}


  function isFixPostalCode(code)
  {
       var postalCode = code;               
       if (postalCode.length == 6)
       {
            match = postalCode.match(/^([ ]*[a-zA-Z][ ]*[0-9][ ]*){3,3}$/g);
            if (match != null)
            {
                var code1 = postalCode.substr(0, 3);
                var code2 = postalCode.substr((postalCode.length-3),3);
                postalCode = code1 + " " + code2;
                return postalCode;
            }
       }     
        return false;
  }

  /**
   * Handler called onclick of button "Search"
   */
  function doStoreSearch(ev) {
	  
	/**
	 * "finder" div has an onclick event to clear search message.
	 * We want to stop onclick event here, so that the search message is not cleared.
	 */
	if (ev) {
	   ev.cancelBubble = true;
	   if (ev.stopPropagation) ev.stopPropagation();
	}

	storeLocator.ResetAll();
	//Do not show error when there is no space in postal code 
	var pos = document.getElementById("txtCloseTo"); 
    if (pos)
       { 
        var FixPostalCode = isFixPostalCode(pos.value);              
	    if (FixPostalCode){	       
	       document.getElementById("txtCloseTo").value = FixPostalCode;
	    }	
	}

	// Validation
	if (elemval("txtCloseTo") == '' || elemval("txtCloseTo") == SLMesg.addressEntryHint) {
		document.getElementById("txtCloseTo").value = "";
		storeLocator.ShowSearchMessage(SLMesg.errAddressEmpty, "");
		return;
	} else if (elemval("txtCloseTo").length < 3) {
		storeLocator.ShowSearchMessage(SLMesg.errAddressNeeds3Chars, SLMesg.searchBoxTip);
		return;
	}
	
	HideIntroControl();
	SLCursor.SetWaitCursor();
    storeLocator.ShowLegend();
	
     /**
      * Set the search flag, 
      * .. then invoke the search.
      */     
     SLMap.ActivateSearchFlag();

     SLMap.GetMap().AttachEvent("onchangeview", mapChangeHandler); // NOTE: hook this event to know when to send our Ajax search	
     
     SLMap.Find(elemval("txtCloseTo"));
	 storeLocator.sendOSTPageNameResult(elemval("txtStoreOffering"),elemval("txtStoreType"));
  }

  /**
   * Class to show error.
   */
  var SLErr = new _SLErr();
  function _SLErr() {
  	
  	/**
  	 * @return a msg when the system is not available.
  	 * NOTE: This can happen:
  	 *   1. when dwr times out (currently 8 sec)
  	 *   2. VE does not respond
  	 *   
  	 * If a simple 'undefined' error: Skip error.
  	 */
  	this.ShowStoreLocatorUnavailableError = function(msg, ex) {
  		
  		storeLocator.ResetAll();// simply reset for the moment
  		SLMap.DeactivateSearchFlag();// for safety
  		
  		/**
  		 * If not fatal message: simply put the error on the console and continue as usual.
  		 */
//  		var errmsg = msg + ": " + exc.message;
//  		
//  		if (ex.message != "timeout") {
//  			SLUtil.debug(errmsg);
//  			return;
//  		}
//  		
//  		var str = '<center><div class="error" id="centralError" style="height:100%;min-height:100%">' 
//  			+ SLMesg.errStoreLocatorUnavailable 						
//  		    + '<br/><table style="height:230px"><tr><td style="vertical-align:bottom">'
//  			+ '<a class="close" href="javascript:window.close();">' + SLMesg.close + '</a>' 
//  			+ '</td></tr></table>'
//  			+ '</div></center>'
//  			+ '<div style="display:none">' + msg + '</div>'; // we hide the msg. Firebug will allow to see it.
//  		
//  		document.getElementById("content").innerHTML = errmsg;
//  		
//        storeLocator.sendOSTPageNameErrorServiceNoAvailable();
  	}
  }
  
  /**
   * Various utilities functions.
   */
  var SLUtil = new _SLUtil();
  function _SLUtil() {
	  
	  /**
	   * @param storeType
	   * @return The store icon in the hilighted mode (Used in Overicons())
	   */
	  this.GetStoreHilightedIcon = function(storeType) {
		  return (storeType == SLConst.BellType  ? 
                  "<img src='/web/common/all_languages/all_regions/images/logos/bell_icon_over.gif' class='overIcon'>" :
                  "<img src='/web/common/all_languages/all_regions/images/logos/other_icon_over.gif' class='otherOver'>");
	  }
	  
	  /**
	   * @param storeType
	   * @return The store icon in the regular mode.
	   */
	  this.GetStoreRegularIcon = function(storeType) {
		  return (storeType == SLConst.BellType ? 
 	      "<img src='/web/common/all_languages/all_regions/images/logos/icon_bell_storeLocator.gif' class='bellPins'>"
		: "<img src='/web/common/all_languages/all_regions/images/logos/icon_orange_storelocatore.gif' class='retailerPins'>" );
	  }
	  
	  /**
	   * @return icon for the center pushpin
	   */
	  this.GetPinIcon = function() {
		  return "/web/common/all_languages/all_regions/images/storeLocator/pin.gif";
	  }
	  
	  /**
	   * @return the legend icons (smaller icons used in the legend section)
	   */
	  this.GetLegendIcon = function(type) {
		 switch (type) {
		 case SLConst.BellType: return "/web/common/all_languages/all_regions/images/icons/mapIco2.gif";
		 case SLConst.OtherType: return "/web/common/all_languages/all_regions/images/icons/mapIco3.gif";
		 case SLConst.PinType: return "/web/common/all_languages/all_regions/images/icons/mapIco1.gif";
		 default: return this.GetLegendIcon(SLConst.BellType);
		}
	  }
	  
	  
	  /**
	   * Perform a firebug console.debug
	   * @param msgm exc exc is exception, if you want to pass it.
	   */
	  this.debug = function(msg, exc) {
		  try {
			  console.debug(msg + " " + _excstr(exc));
		  } catch(e) {
		  }
	  }

	  /**
	   * @return detailed exception str
	   */
	  function _excstr(exc) {
		  if (!exc) return "";
		  return  " ===> EXCEPTION: " + exc.name + "[" + exc.message + "]";
	  }	  
  }

  /**
   * From http://www.htmlcodetutorial.com/forms/index_famsupp_157.html.
   * Submits the search on Enter key.
   * To be placed in the body
   * @param myfield
   * @param e
   * @return
   */
  function submitEnter(ev) {	  
	
	var keycode;
	
	if (!ev) {
		return true;
	}

	if (ev.keyCode == 13) {
//		doStoreSearch(ev);
//		return false;

		// If user is entering route address: Cancel the Enter...
		if (SLBub.IsBubShown() && document.getElementById("routeAddressTxt")) {
			   return false;
		} else {
			// otherwise do the search...
			doStoreSearch(ev);
			return false;
		}
	} else {
		return true;
	}
  }
  
  function elemval(elemid) {
     return document.getElementById(elemid).value;
  }