﻿/* ---- Store Locator ---- */

var globalmap;

(function() {

    var StoreLocatorController = {
        element: null,
        init: function() {
            //Create the Out of the box Map object
            if (!$('#locatorMap')) return; //First we check the locatorMap HTMLElement exists.
            this.element = document.getElementById("txtLocation"); //$('#txtLocation') does not seem to work.
            try { globalmap = new VEMap('globalMap'); } catch (Error) { }

            if (!globalmap) return false;
            var el = this.element;
            var elCoords = $(el).position();


            var relativeParent = $("#locator");
            var relativeParentCoords = relativeParent.position();
            var dropdown = $("#globalAmbig");
/*
            dropdown.css({
                "top": relativeParentCoords.top + 54,
                "left": relativeParentCoords.left + 7
            });
*/

            //Attach events to the field
            var controller = this;
            $(el).keypress(function(evt) {
                switch (evt.which) {
                    case 13: controller.execute(el.value); break;
                    default: return true;
                }
                return false;
            });
            //Attach an onblur event to the input, so that we can hide the search results
            $(el).blur(function() {
                dropdown.fadeOut();
            });

            //Attach a click event to the Store Locator Go Button
            //re-use the functionality of a keypress on the input box.
            $('#storeLocatorGo').click(function() {
                controller.execute(el.value);
                return false;
            });
        },
        execute: function(value) {
            //Consume the Maps Web Service
            globalmap.LoadMap();
            var controller = this;
            try {
                globalmap.Find(
			        null, // what
			        value, // where
			        null, // find type
			        null, // shape layer
			        null, // start index
			        null, // number of results
			        false, // show results (show pushpins?)
			        false, // create results (create pushpins?)
			        false, // default disambig
			        false, // set best map view?
			        controller.onResponse	// callback
		        );
            }
            catch (error) {
                alert("There was an error processing " + value + " : " + error.message);
            }
            return false;
        },
        onResponse: function(layer, results, places, hasmore) {
            // Results null or empty.
            if ((places === null) || (typeof places === 'undefined') || places.length === 0) {
                alert("No results found");
                return false;
            }
            geocodeResults = places;

            // One result, proceed with find nearby of Starbucks locations.
            if (places.length === 1) {
             
                // fill hidden field with data
                var hdn = document.getElementById("hdnGlobalLocation");
                var where = document.getElementById("txtLocation").value;
                var dataString = escape(where) + "|" + geocodeResults[0].LatLong.Latitude + "|" + geocodeResults[0].LatLong.Longitude;

                hdn.value = dataString;

                //post form to locationResults
                var formActionFormatString = 'http://www.starbucks.com/Retail/Find/LocatorResults.aspx';
                formActionFormatString += '?fs=1&loc=' + dataString;
                document.forms[0].action = formActionFormatString;

                // Re-set filters going to the results page.
                //document.forms[0].submit();
                window.location.href = formActionFormatString;
            }
            // Ambiguous results found, update panel.
            else {

                // fill ambigs with links to results page.
                var ambigHTML = "<p>Did you mean&hellip;</p><ol>";
                var formatString = "<li><a href='javascript:onFoundResultsHelperGlobal({1});'>{2}</a></li>";
                for (var i = 0; i < places.length; i++) {
                    ambigHTML += formatString.replace("{1}", i).replace("{2}", places[i].Name);
                }
                ambigHTML += "</ol>";

                var ambigDiv = document.getElementById("globalAmbig");
              
                ambigDiv.innerHTML = ambigHTML;
                //ambigDiv.style.display = "block";
                $('#globalAmbig').fadeIn();
            }

        }
    };

    //on ready of the document, initialize the storeLocator
    $(document).ready(function() {
        StoreLocatorController.init();
    });
})();

//Reuse this function for post to form.
function onFoundResultsHelperGlobal(index) {
	// fill hidden field with data
	// post form to locationResults                    
	var hdn = document.getElementById("hdnGlobalLocation");
	var where = document.getElementById("txtLocation").value;
	var dataString = escape(where) + "|" + geocodeResults[index].LatLong.Latitude + "|" + geocodeResults[index].LatLong.Longitude;

	hdn.value = dataString;

	// post form to locationResults
	var formActionFormatString = 'http://www.starbucks.com/Retail/Find/LocatorResults.aspx';
	formActionFormatString += '?fs=1&loc=' + dataString;
	document.forms[0].action = formActionFormatString;
	window.location.href = formActionFormatString;
}