jQuery.wtb = {};

// TURN WTB ON (true) OR OFF (false)
jQuery.wtb.globalSwitch = true;

// Options for Places search results
jQuery.wtb.placesMaxResults = 25;  // Max results per vendor pre-sorting
jQuery.wtb.placesMaxShown = 26;  // Hard limit due to letter-based markers
jQuery.wtb.placesRadius = 32186.88;  // In meters
jQuery.wtb.placesTypes = ['store','shopping_mall'];  // Google types to restrict results to
jQuery.wtb.placesVendors = ['walmart','target','kmart','toys r us'];  // List of store chains to filter results to
jQuery.wtb.placesFilters = ['pharmacy','vision','health','photo','bakery','connection'];  // List of key words or types to exclude
jQuery.wtb.mapZoom = 10;  // Default map zoom
jQuery.wtb.merchandIDs = "7804187|2860562|1113342|10046|1324698|4008471|7906|6382239|3359942";  // List of Buy Online merchant IDs

// Messages & Errors
jQuery.wtb.loadingText = "Loading your local map!  Your browser may ask you for permission to share your location.";
jQuery.wtb.errorNoResults = "Sorry, there don't seem to be any results for that location.  Please enter a new location to try again!";	
jQuery.wtb.errorMapLoad = "There was a problem loading the map.  Please try again later!";
jQuery.wtb.errorValidLocation = "Please enter a valid city and state or a zip code:";
jQuery.wtb.errorLocation = "We were unable to automatically determine your location.  Please enter it below to get local results:";
jQuery.wtb.messagePermission = "We'd like to show you nearby stores!";
jQuery.wtb.messageBuyOnline = "This item doesn't appear to be available online.";

/* Do not edit below this line! */
jQuery.wtb.placesTotal = 0;  // Global var to track looping
jQuery.wtb.placesMaster = [];  // Global var for filtered place results
jQuery.wtb.locationCookie = jQuery.cookie('wtb-location');
jQuery.wtb.s = s;
jQuery(document).ready(function() {
		
	/****** Options ******/
	/*********************/	
	// Show Buy Online section
	var buyOnlineOn = true;
	// Show Buy Nearby section
	var buyNearbyOn = true;
	//  Fallback to use if your browser can't support geo-location.  Options are "ask" to ask 
	//  the user for location and "google" to ask Google for location, or "error" to just show a basic error.
	var mapFallback = "ask";	
	/*************************/
	/****** End Options ******/
	
	var gApiKey = "AIzaSyBjk4UH5GQa-dTp_YgxuFIpQkL1vUKXEE0";
	var gtin = jQuery("#gcs-gtin").text();
	
	// Check for a gtin on the product and fire the onclick if it exists.
	if (gtin && gtin != "" && jQuery.wtb.globalSwitch) {
	
		//a where to buy button is clicked
		jQuery('.wtb_button').click(function(){
            var wtbButton = jQuery(this);
			jQuery.getScript("/includes/xgls/?" + (new Date().getTime() + '_' + Math.floor(Math.random() * 1000000)), function(data, textStatus) {
                //geoData and geoLocation variables should now be defined and populated.

                //find the corresponding dialog box
                var wtb_dialog_message = jQuery('#' + wtbButton.attr('id') + '_dialog');

                //if it doesn't exist, create it
                if (! wtb_dialog_message[0]) {

                    //extract the sku from the name
                    var sku = wtbButton.attr('name');

                    //scrape title, description and img from other elements, tied by sku
                    var title = jQuery(".hsb_brand_sect_hdr h1").html();
                    var description = jQuery(".pdp_description").html().replace("<p></p>","");
                    var imgsrc = jQuery('#hsb_shop_pdp_photos_img').attr('src');
                    var mapError = "<div id='map-error'></div>";
                    var locationError = "<div id='location-error'></div>";

                    //create the dialog box
                    wtb_dialog_message = jQuery('<div id="'+ wtbButton.attr('id') + '_dialog" title="Where to Buy" class="wtb_dialog"></div>');
                    wtb_dialog_message.append("<img class='wtbimg' src='" + imgsrc + "' />");
                    wtb_dialog_message.append("<div class='wtb-desc'><h4>" + title + "</h4>" + description + "</div>");
                    var buyonlinediv = jQuery("<div id='buy-online'></div>").appendTo(wtb_dialog_message);
                    var buynearbydiv = jQuery("<div id='buy-nearby'></div>").appendTo(wtb_dialog_message);

                    //append to the dom after the wtb button, not that it matters where...
                    wtbButton.after(wtb_dialog_message);

                    //----
                    // Now do the API calls to populate the dialog
                    //----

                    // If buyOnlineOn is on...
                    if (buyOnlineOn) {

                        //this is sku, atin and/or gtin - we need all these for a product...
                        //var gQuery = "653569601777|c36473fd";
                        var gQuery = gtin;

                        //need to add further restrictions, only new products, other?
                        var apiUrl = "https://www.googleapis.com/shopping/search/v1/public/products?country=US&language=en&alt=json&restrictBy=accountId=" + jQuery.wtb.merchandIDs + "&q=" + escape(gQuery) + "&key=";

                        //do a json call, important to add callback parameter to force jQuery to use jsonp, cross-domain, https, etc.
                        jQuery.getJSON(apiUrl + gApiKey + "&callback=?",function(data) {

                            buyonlinediv.append("<div class='buy-online'></div>");

                            if (data.items) {
                                //build and append a table
                                var buyonlinetable = jQuery("<table border='0' cellspacing='0' cellpadding='0'></table>");
                                buyonlinetable.append("<tr id='headings'><th class='bo-name'>Store</th><th class='bo-price'>Price</th><th class='bo-ship'>Est. Shipping</th><th class='bo-total'>Est. Total</th><th class='bo-button'>Buy</th></tr>");

                                //go through each item and build the row
                                for (displayItem in data.items) {
                                    if (typeof data.items[displayItem].product !== 'undefined') {
                                        var row = jQuery("<tr id=" + data.items[displayItem].product.author.accountId + ">");
                                        var total = Math.round((data.items[displayItem].product.inventories[0].price + data.items[displayItem].product.inventories[0].shipping) * 100) / 100;
                                        var vendorName = data.items[displayItem].product.link.split("/");

                                        var newHref = "";
                                        if (String(data.items[displayItem].product.author.accountId) == "7804187") {
                                            newHref = data.items[displayItem].product.link + " target=\"_blank\"";
                                        } else {
                                            newHref = "javascript:popupPageleave('/includes/leave.cfm?new_win=true&url=" + data.items[displayItem].product.link + "')";
                                        }

                                        if (String(data.items[displayItem].product.author.accountId) == "7804187") {
                                            row.append("<td class='bo-name'><a href=" + newHref + " id='HTS'>" + vendorName[1] + vendorName[2] + "</a></td>");
                                        } else {
                                            row.append("<td class='bo-name'><a href=" + newHref + " id='" + data.items[displayItem].product.author.name + "'>" + vendorName[1] + vendorName[2] + "</a></td>");
                                        }
                                        
                                        row.append("<td class='bo-price'>" + data.items[displayItem].product.inventories[0].price + "</td>");
                                        row.append("<td class='bo-ship'>" + data.items[displayItem].product.inventories[0].shipping + "</td>");
                                        row.append("<td class='bo-total'>" + total + "</td>");
                                        row.append("<td class='bo-button'><a class='buy-now' href=" + newHref + ">Buy Now</a></td>");
                                        buyonlinetable.append(row);
                                    }
                                }

                                //append the table to the dialog
                                buyonlinetable.appendTo(buyonlinediv);

                                // Format currency
                                jQuery('td.bo-price').add('td.bo-ship').add('td.bo-total').formatCurrency();

                                // Put HTS on top
                                jQuery("tr#7804187").insertAfter("#headings");
                                jQuery("tr#7804187").find(".bo-name a").addClass("hts");

                                //zebra stripes
                                buyonlinetable.find("tr:nth-child(odd)").addClass("odd");

                                if (data.items.length >= 5) {
                                    // Wrap table in a scrolling div
                                    buyonlinetable.wrap("<div id='buy-online-scroll'></div>");
                                }

                            } else {
                                // No item results
                                jQuery(".buy-online").after("<div id='bo-no-results'>" + jQuery.wtb.messageBuyOnline + "</div>");
                            }

                        }); // finish api call for buy online
                    }

                    //----
                    // Buy Nearby
                    //----

                    // If buy nearby is enabled...
                    if (buyNearbyOn) {
                        // Show permissions window to allow the user to detect location or enter one manually.
                        buynearbydiv.append("<div class='buy-nearby'></div><div class='nearby-permission'><div class='message'>"+ jQuery.wtb.messagePermission + "</div><div class='inputs'></div></div>");
                        var initialValue = "Enter Zip Code or City, State";
						
						if (geoData == "error") {
							var permissionBox = jQuery("<input id='enter-location' type='text' value='" + initialValue + "' />").appendTo(".nearby-permission .inputs");
							jQuery(".nearby-permission .inputs").css("text-align","center");
						} else {
                        	var permissionBox = jQuery("<a href='#' id='detect-location' onclick='return false;'>Use Current Location</a><span>or</span><input id='enter-location' type='text' value='" + initialValue + "' />").appendTo(".nearby-permission .inputs");
						}
						
                        var permissionGoButton = jQuery("<input id='enter-location-button' type='button' value='Go' />").click(function(){
                            var input = jQuery("#enter-location").val();
                            jQuery(".nearby-permission").hide();
                            updateLocation(input, "permission");
                        }).appendTo(".inputs");

                        jQuery("#enter-location").live("click",function(){
                            jQuery(this).val("");
                        }).keydown(function(e){
                            var keycode = e.which;

                            if (keycode == 13) {
                                jQuery("#enter-location-button").trigger("click");
                            }
                        });

                        //create containers for user location, map and results
                        var nearbylocation = jQuery("<div id='location'><div class='location-inputs' style='display: none;'></div></div>").appendTo(buynearbydiv);
                        var mapdiv = jQuery("<div class='mapdiv'></div>").appendTo(buynearbydiv);
                        var nearbyresults = jQuery("<div class='nearbyresults'><div id='places-results'></div></div>").appendTo(buynearbydiv);
                        jQuery(locationError).insertBefore("#location");
                        jQuery(mapError).prependTo(".nearbyresults");

                        // User clicks on "Use my location" button
                        jQuery("#detect-location").live("click", function() {
                            jQuery(".nearby-permission").hide();

                            //create input box and button for user location
                            var changeLocationInput = jQuery("<input id='current-location' type='text' />").appendTo("#location .location-inputs");

                            var changeGoButton = jQuery("<input id='change-location-button' type='button' value='Go' />").click(function(){
                                var input = jQuery("#current-location").val();
                                updateLocation(input, "change");
                            }).appendTo("#location .location-inputs");

                            jQuery("#current-location").keydown(function(e){
                                var keycode = e.which;

                                if (keycode == 13) {
                                    jQuery("#change-location-button").trigger("click");
                                }
                            });

                            // Detect location
                            var visitor_lat;
                            var visitor_lon;
                            var visitor_city;
                            var visitor_region;
                            var myLatlng;
                            var yourlocation;
                            var yourchange;

                            // Does this browser allow detecting location?
                            if (geoData) {

                                jQuery(".nearby-loading").hide();

                                visitor_lat = geoData.lat;
                                visitor_lon = geoData.long;

                                var sortLatLong = { lat: visitor_lat, lng: visitor_lon };

                                //reset the map center and add a marker
                                myLatlng = new google.maps.LatLng(visitor_lat, visitor_lon);
                                hasMap(mapdiv,nearbyresults,myLatlng,sortLatLong);

                                //create the text version of the location, with a change link
                                yourlocation = jQuery("<div class='nav-geo' style='text-transform: capitalize;'>Your Location: " + geoData.city.toLowerCase() + ", " + geoData.region_code + " </div>");
                                wtbCookie(geoData.city.toLowerCase() + ", " + geoData.region_code);

                                yourchange = jQuery("<a href='#'>Change Location</a>").click(function(){
                                    yourlocation.remove();
                                    jQuery(".location-inputs").show();
                                    changeLocationInput.val(geoData.city + ", " + geoData.region_code);
                                });

                                yourlocation.append(yourchange);
                                nearbylocation.append(yourlocation);

                            // Switch to Google for location
                            } else {
                                if (mapFallback == "ask") {
                                    jQuery(".nearby-loading").hide();
                                    jQuery("#map-error").add("#location-error").hide();
                                    jQuery("#location-error").text(jQuery.wtb.errorLocation).addClass("error-geo-failed").show();
                                    jQuery(".location-inputs").css('display','block');
                                }
                            }
                        });

                        // Check for existing cookie
                        if (jQuery.wtb.locationCookie && jQuery.wtb.locationCookie != null) {
                            jQuery(".nearby-permission").hide();
                            updateLocation(jQuery.wtb.locationCookie, "permission");
                        }

                    } // End buyNearby

                } // if the dialog box didn't exist, create it

                // Make the dialog box into a... dialog
                wtb_dialog_message.dialog({
                    modal: true,
                    buttons: {
                        Close: function() {
                            jQuery( this ).dialog( "close" );
                        }
                    },
                    width: 640,
                    minWidth: 640,
                    minHeight: 200
                });

                //Set Omniture stuff...
                var _s = s_gi(s_account);
                _s.linkTrackVars = "prop1,eVar1,prop12,eVar12,prop15,eVar15,prop47,eVar47,pageName,events";
                _s.linkTrackEvents='event22';
                var pn = jQuery.wtb.s.pageName.split(":");
                if (pn && pn.length >= 4) {
                    _s.pageName = pn[0] + ":" + pn[1] + ":" + pn[2] + ":where to buy";
                } else {
                    _s.pageName = jQuery.wtb.s.pageName + "where to buy";
                }
                _s.prop1 = _s.eVar1 = jQuery.wtb.s.prop1;
                _s.prop12 = _s.eVar12 = jQuery.wtb.s.prop12;
                _s.prop15 = _s.eVar15 = "where to buy";
                _s.prop47 = _s.eVar47 = jQuery.wtb.s.prop47;
		        _s.events='event22';
                _s.tl(_s, 'o', "where to buy");
            });
            return false;
		});
	}	
});

///make a map, center it, add a marker, and do a lookup of stores nearby and add markers
function hasMap(mapdiv, nearbyresults, myLatlng, sortLatLong) {
	//clear the map and results
	mapdiv.html('');
	jQuery("#places-results").html('');
	jQuery.wtb.placesMaster = [];
	jQuery("#map-error").add("#location-error").text("").hide();
	jQuery(".nearbyresults").add(".mapdiv").css("display","block");

	//create the map, no center, just initialize
	var map;
    var myOptions = {
      zoom: jQuery.wtb.mapZoom,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(mapdiv[0],myOptions);

	//center it
    map.setCenter(myLatlng);

	//mark it with a blue
    var youMarker = new google.maps.Marker({
        map: map, 
        position: myLatlng,
		zIndex: 1000,
		icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',
		title: 'You Are Here'
    });

	jQuery.wtb.placesSearchIncrement = jQuery.wtb.placesVendors.length;
	// Run Places queries for each name listed in placesVendors
	for (var i = 0; i < jQuery.wtb.placesVendors.length; i++) {
		placesSearch(jQuery.wtb.placesVendors[i], myLatlng, sortLatLong, map);
	};	
}

// Function to sort store results promise
function sortStoreResultsPromise(sortLatLong, map, service) {
	if (jQuery.wtb.placesMaster.length > 0) {
		--jQuery.wtb.placesSearchIncrement;
		if ( jQuery.wtb.placesSearchIncrement <= 0 ) {
			var sortedPlaces = sortStoreResults(sortLatLong, jQuery.wtb.placesMaxShown, jQuery.wtb.placesVendors, jQuery.wtb.placesMaster);
			
			for (var i = 0; i < sortedPlaces.length; i++) {
				// Loop through place details for sortedPlaces	
				var place = sortedPlaces[i];
				var markerIndex = 1000 - i;
				var marker = new google.maps.Marker({
					map: 		map, 
					position: 	place.geometry.location,
					icon: 		'http://maps.google.com/mapfiles/marker' + String.fromCharCode(jQuery.wtb.placesTotal + 65) + '.png',
					name: 		place.name,
					reference: 	place.reference,
					title: 		place.name,
					zIndex: 	markerIndex
				});
				markerNumber = "marker" + String.fromCharCode(jQuery.wtb.placesTotal + 65);
				marker.set("id", markerNumber);
				
				var selectedDefault = "";			
				if (String.fromCharCode(jQuery.wtb.placesTotal + 65) == "A") {
					selectedDefault = "selected";
				}
			
				// Add place to results
				if (place.id && place.name) {
					var placeLink = jQuery("<a href='#' class='" + selectedDefault + "' id='" + place.id + "' name='" + jQuery.wtb.placesTotal + "'><img src='http://maps.google.com/mapfiles/" + markerNumber + ".png'><span class='place-name'></span><div class='info'></div></a>");
					jQuery(".nearbyresults #places-results").append(placeLink);
				}
				
				// Attach marker click events
				attachListener(marker, jQuery.wtb.placesTotal, place.id);
				
				// Get Place details
				service.getDetails({reference: 	place.reference}, (function(detailed, status) {
					var placeID = jQuery("#" + detailed.id);
					var address = "";
					var zip = "";
					var call = "";
					var newHref ="";
					var newAddress = detailed.formatted_address.split(",")[0] + ", " + detailed.formatted_address.split(",")[1] + ", " + zip;
					
					// Error check each data type				
					if (detailed.formatted_address && detailed.formatted_address.length > 3) {
						address = detailed.formatted_address.split(", ");
						if (address[2]) {
							zip = address[2].split("-")[0];
						}
						newAddress = detailed.formatted_address.split(",")[0] + ", " + detailed.formatted_address.split(",")[1] + ", " + zip;
					}				
					if (detailed.formatted_phone_number && detailed.formatted_phone_number.length > 3) {
						call = "Call for Availability: " + detailed.formatted_phone_number;
					}
					if (detailed.url && detailed.url.length > 3) {
						newHref = "javascript:popupPageleave('/includes/leave.cfm?new_win=true&url=" + detailed.url.replace("maps/place","") + "')";
					}		
					
					placeID.attr("href", newHref).find("span").text(detailed.name);
					placeID.find("div.info").append(newAddress + "<br/>" + call);
				}));
				
				jQuery.wtb.placesTotal++;
			}	
		}
	} else {
		jQuery("#map-error").add("#location-error").hide();
		jQuery("#map-error").text(jQuery.wtb.errorNoResults).addClass("error-no-results").show();
	}
}

// Function to run a seach on a vendor name
function placesSearch(vendorName, myLatlng, sortLatLong, map) {
	
	// query google for local results
	var request = {
		location: myLatlng,
		radius: jQuery.wtb.placesRadius,
		types: jQuery.wtb.placesTypes,
		name: vendorName
	};
	
	var service = new google.maps.places.PlacesService(map);
	service.search( request, (function(results, status) {
		if (status == google.maps.places.PlacesServiceStatus.OK) {
	
			//limit the results
			if (results.length < jQuery.wtb.placesMaxResults) {
				jQuery.wtb.placesMaxResults = results.length;
			}
			
			var markers;
			
			for (var i = 0; i < jQuery.wtb.placesMaxResults; i++) {
				
				// Iterate through search results...			
				var placeDetails;
				var place = results[i];
				var request = {reference: place.reference};
				
				var findFilter = false;
				// Filter results based on list of words to exclude
				jQuery.each(jQuery.wtb.placesFilters, function(index, value) {
					var typeFound = jQuery.inArray(value, place.types);
					var nameFound = place.name.toLowerCase().indexOf(value);
					if (typeFound > 0 || nameFound > 0) {
						findFilter = true;
					};
				});
				
				// If the filtered word was not found, add it to the map...
				if (!findFilter && place.name && jQuery.wtb.placesTotal < jQuery.wtb.placesMaxShown) {
					jQuery.wtb.placesMaster.push(place);
				}
			}
						
		} else if (status == "OVER_QUERY_LIMIT") {
		  // Handle an over-query-limit error from Places
		  jQuery("#map-error").add("#location-error").hide();
		  jQuery("#location-error").text(jQuery.wtb.errorMapLoad).addClass("out-of-calls").show();		  
		  jQuery("#location").add(".mapdiv").add(".nearbyresults #places-results").hide();	  
		} else if (status == "ZERO_RESULTS") {
			// Handle zero results error from Places
			
		}
		sortStoreResultsPromise(sortLatLong, map, service, request);
	}));
}

// Function to attach custom click functionality to each marker
function attachListener(marker, number, id) {
  google.maps.event.addListener(marker, 'click', function() {
	var scrollHeight = jQuery("#" + id).outerHeight(true) * jQuery("#" + id).attr("name");
    jQuery("#places-results a").removeClass("selected");
	jQuery("#" + id).addClass("selected");				
	jQuery('#places-results').animate({ scrollTop: scrollHeight}, 'slow');
  });
};

//---
// Click tracking
//---

function wtbClickTrack(link,text,type) {
	// Define Omniture Event
	var omEvent = "None";
	var omFriendlyName = "";
	switch (type) {
		case 'local-retailer':
			omEvent = "event30";
			omFriendlyName = "WTB Local Retailer Click";
			break;			
	};
	
	// Build Ominture Call
	var s_wtb = s_gi(site_account);
	s_wtb.linkTrackVars = "events";
	s_wtb.linkTrackEvents = omEvent;
	s_wtb.events = omEvent;
	
	/* Alert for testing tracking data sent
	alert(
		"LTV = " + s.linkTrackVars + " || " +
		"LTE = " + s.linkTrackEvents + " || " +
		"search term = " + omSearchTerm + " || " +
		"event = " + omEvent + " || " + 
		"FN = " + omFriendlyName	
	);*/
	
	s_wtb.tl(this,"o",omFriendlyName);
}

//monitor local retailer clicks
jQuery('.nearbyresults #places-results a').live('click', function(){
	wtbClickTrack(jQuery(this).attr('href'),"",'local-retailer');
});

//Track buy online retailer links
jQuery(".bo-name a, .bo-button a").live("click", function() {
	var retailer = jQuery(this).parent().parent().find(".bo-name a").attr("id");
    var last_product = jQuery(".wtb-desc h4").text();
	wtb_tracking_Click('retail ' + retailer,'retail button','retail link click', last_product);
});

jQuery(".ui-widget-overlay").live("click", function() {
	jQuery(".ui-dialog-titlebar-close").trigger("click");
});

// Cookie function
function wtbCookie(value) {
	var date = new Date();
	date.setTime(date.getTime() + (30 * 60 * 1000));
	jQuery.cookie('wtb-location', value, { expires: date, path: '/' });
	jQuery.wtb.locationCookie = value;
}

var sortStoreResults = function(location, limit, storeList, unsortedList) {
	var lat1 = location.lat;
	var lng1 = location.lng;
	var stores = [];
	var i = 0;
	
	//Loop through our results, appending our distance calculation so later on we can Sort them.
	for (i = 0; i < unsortedList.length; ++i) {
		var lat2 = unsortedList[i].geometry.location.Na;
		var lng2 = unsortedList[i].geometry.location.Oa;
		
		//Calculate the distance between 2 points.
		var rho = 3960.0; // earth diameter in miles
		var phi1 = (90.0 - lat1) * Math.PI / 180.0;
		var phi2 = (90.0 - lat2) * Math.PI / 180.0;
		var theta1 = lng1 * Math.PI / 180.0;
		var theta2 = lng2 * Math.PI / 180.0;
		unsortedList[i].distance = rho * Math.acos( Math.sin(phi1) * Math.sin(phi2) * Math.cos(theta1 - theta2) + Math.cos(phi1) * Math.cos(phi2) );
	}
	
	//Sort by the calculated distance...
	var sortedList = unsortedList.sort(function(a, b) {
		return a.distance == b.distance ? 0 : (a.distance < b.distance ? -1 : 1);
	});
	
	//Loop through the results and the storeList and grab one of each store available...
	for (i = 0; i < storeList.length; ++i) {
		var y = 0;
		var match = false;
		while(!match) {
			if (sortedList.length <= y) {
				match = true;
			}
			if (!match && sortedList[y].name.toLowerCase().indexOf(storeList[i]) != -1) {
				stores.push(sortedList[y]);
				sortedList.splice(y, 1);
				match = true;
			} else {
				++y;
			}
		}
	}
	
	//Sort these stores...
	stores.sort(function(a, b) {
		return a.distance == b.distance ? 0 : (a.distance < b.distance ? -1 : 1);
	});
	
	//Pad the results up to the limit... or crop them.
	if (stores.length < limit) {
		while (stores.length < limit && sortedList.length) {
			stores.push(sortedList.shift());
		}
	} else if (stores.length > limit) {
		stores = stores.splice(0, limit);
	}
	
	return stores;
};

// GET USER LOCATION - INPUT
function updateLocation(input, type) {
	jQuery("#places-results").html('');						
	jQuery("#map-error").add("#location-error").text("").hide();
	wtbCookie(input);
	var yourlocation;
	var yourchange;
	var initialValue = "Enter Zip Code or City, State";
	
	if (type == "permission") {
		//create input box and button for user location
		var changeLocationInput = jQuery("<input id='current-location' type='text' />").appendTo("#location .location-inputs");													
		var changeGoButton = jQuery("<input id='change-location-button' type='button' value='Go' />").click(function(){
			var input = jQuery("#current-location").val();
			updateLocation(input, "change");
		}).appendTo("#location .location-inputs");
									
		jQuery("#current-location").live("click",function(){
			jQuery(this).val("");
		}).keydown(function(e){
			var keycode = e.which;			
			if (keycode == 13) {
				jQuery("#change-location-button").trigger("click");
			}
		});
					
		//create the text version of the location, with a change link
		yourchange = jQuery("<a href='#'>Change Location</a>").click(function(){
			jQuery(".nav-geo").remove();
			jQuery(".location-inputs").show();
			jQuery("#current-location").val(input.toLowerCase());
		});
		
		jQuery(".location-inputs").show();
		jQuery("#current-location").val(input.toLowerCase());
		
	} else if (type == "change") {
		//create the text version of the location, with a change link
		yourchange = jQuery("<a href='#'>Change Location</a>").click(function(){
			jQuery(".nav-geo").remove();
			jQuery(".location-inputs").show();
			//jQuery("#current-location").val(geoData.city + ", " + geoData.region_code);
		});
		
		//jQuery(".nav-geo").text("Your Location: " + geoData.city.toLowerCase() + ", " + geoData.region_code);
	}
		
	if ( input != "" && input != initialValue && input.length > 3 ) {
		jQuery.wtb.placesTotal = 0;
		jQuery("#map-error").add("#location-error").hide();
		jQuery("#places-results").html("");
		//when the button is clicked, geocode it and reset the map
		geocoder = new google.maps.Geocoder();
		var address = input;
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var sortLatLong = { lat: results[0].geometry.location.Na, lng: results[0].geometry.location.Oa };
				hasMap(jQuery(".mapdiv"),jQuery(".nearbyresults"),results[0].geometry.location,sortLatLong);
			} else {
				jQuery("#map-error").add("#location-error").hide();
				jQuery("#map-error").text(jQuery.wtb.errorNoResults).addClass("error-no-results").show();
			}
		});
	} else {
		jQuery("#map-error").add("#location-error").hide();
		jQuery("#location-error").text(jQuery.wtb.errorValidLocation).addClass("error-valid-location").show();
	}
}

var popupPageleaveLarge = function(URL) {
    self.name = "main"; aWindow=window.open(URL,"thewindow","toolbar=1,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1");
};
