//Define event listeners
$(document).ready(function(){
	initMap();
});
$(window).unload(function() {
	GUnload();
});

var gmap, p;
var exml = null;

var spinnerCode = '<div style="padding:10px 10px 0;float: right;"><img src="/images/ajaxspinners/circleball.gif" border="0"></div>';
var emailSignupSpinnerCode = '<img src="/images/ajaxspinners/circleball.gif" border="0">';

var initMapCenter = new GLatLng(37.02009820136811, -98.173828125);

var coverageSearchButton = '';
var zoomSwitchThreshhold = 6;
var zoomendReCenter = true;

var skipzl = false;
var print_window;

var searchInfoWin = null;
var searchMarker = null;

var overlay_color = '';

var geocoder = null;

var coverageOverlay = null;
var stateOverlay = null;
var currentOverlay = null;

var stateFillOver = {opacity: '0.3'};
var stateFillNormal = {opacity: '0.5'};

var isInitialShopZipPopupShown = false;

function Hash() {}

function showOverlay(overlay) {
	if (currentOverlay == overlay) return;
	if (currentOverlay != null) {
		gmap.removeOverlay(currentOverlay);
	}
	currentOverlay = overlay;
	gmap.addOverlay(currentOverlay);
}

function setLegend(){
	var z = gmap.getZoom();
	if(z == 4) {
		// hide the zoom controls on default zoom view
		$('.gmnoprint').each( function() { $(this).hide(); });
	} else {
		$('.gmnoprint').each( function() { $(this).show(); });
	}
	if(z < zoomSwitchThreshhold ){
		if ($('#legend-zoom')) 			{ $('#legend-zoom').hide(); }
		if ($('#cbox_legend_btm')) 		{ $('#cbox_legend_btm').hide(); }

		if ($('#legend-overview')) 		{ $('#legend-overview').show();  }
		if ($('#cbox_legend_btm_zoom')) 	{ $('#cbox_legend_btm_zoom').show(); }
	} else {
		if ($('#legend-zoom')) 			{ $('#legend-zoom').show(); }
		if ($('#cbox_legend_btm')) 		{ $('#cbox_legend_btm').show(); }

		if ($('#legend-overview')) 		{ $('#legend-overview').hide(); }
		if ($('#cbox_legend_btm_zoom')) 	{ $('#cbox_legend_btm_zoom').hide(); }
	}
}

function isBrowserIE(ver) {
  var ievs = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
  if (ievs) {
    if (ver) {
		var iev=new Number(RegExp.$1);
	    if (iev==ver) {
	      return true;
	    } else {
	    	return false;
	    }
    }
    return true;
  }
  return false;
}

//--------------------------------------------------------------------------------
function switchLayers() {

	setLegend();

	try {
		if (!skipzl) {
			skipzl = true;
			var z = gmap.getZoom();

			if (z < zoomSwitchThreshhold) {
				//The zoom level is below the threshhold
				//so display the state overlay
				if (stateOverlay == null) {
				  if(isBrowserIE(6) === true)
				  {
				    stateOverlay = createIE6StateOverlay(coveragetype);
				  } else {
				    stateOverlay = createStateOverlay(coveragetype);
				  }
				}
				if (stateOverlay != null) {
					showOverlay(stateOverlay);
					/*
					if (z == zoomSwitchThreshhold - 1) {
						if (zoomendReCenter) {
							//Center the map at this zoom level
							gmap.setCenter(initMapCenter);
						} else {
							zoomendReCenter = true;
						}
					}
					*/
					gmap.setZoom(4);
					gmap.setCenter(initMapCenter);
				}
			} else {
				//The zoom level is above the threshhold
				//so display the coverage overlay
				if (coverageOverlay == null) {
					coverageOverlay = createCoverageOverlay(coveragetype);
				}
				if (coverageOverlay != null) {
					showOverlay(coverageOverlay);
				}
			}
			skipzl = false;
		}
	} catch (e) {
		alert(e.message);
		skipzl = false;
	}
}

function createCoverageOverlay(type){
	//change tile layer source based upon coverage type
	var tilelayer = null;
	if (isBrowserIE()) {
		tilelayer = new GTileLayer(null, null, null, {
			tileUrlTemplate: GEOMAP_URL+'?layers=cricket:'+type+'&zoom={Z}&x={X}&y={Y}&format=image/gif', isPng:false, opacity:0.5 });
	} else {
		tilelayer = new GTileLayer(null, null, null, {
			tileUrlTemplate: GEOMAP_URL+'?layers=cricket:'+type+'&zoom={Z}&x={X}&y={Y}', isPng:true, opacity:0.5 });
	}

	//gmap.clearOverlays();
	var overlay = new GTileLayerOverlay(tilelayer);
	return overlay;
}

function createIE6StateOverlay(type){
	//change tile layer source based upon coverage type
	var tilelayer =  new GTileLayer(null, null, null, {
	tileUrlTemplate: GEOMAP_URL+'?layers=cricket:'+type+'_states&zoom={Z}&x={X}&y={Y}&format=image/gif', isPng:false, opacity:0.5 });
	//gmap.clearOverlays();

	var overlay = new GTileLayerOverlay(tilelayer);
	return overlay;
}

function createStateOverlay(type) {
  var kmlSource = '';

  if (type == 'broadband') {
	 kmlSource = 'http://www.mycricket.com/kml/states_broadband.kml?20100108';
  } else {
	 kmlSource = 'http://www.mycricket.com/kml/states_voice.kml?20100108';
  }

  if (kmlSource != '') {
    GEvent.addListener(gmap, "addoverlay", function(poly) {
      try {
        if (poly instanceof GPolygon) {
          var state = poly;
          state.stateFillStyle = stateFillNormal;
          state.clickable = true;

          GEvent.addListener(state, "mouseover", function() {
            state.setFillStyle(stateFillOver);
          });

          GEvent.addListener(state, "mouseout", function() {
            state.setFillStyle(stateFillNormal);
          });

          GEvent.addListener(state, "click", function(latlng) {
        	var czoom = gmap.getBoundsZoomLevel(state.getBounds());
        	if (czoom < zoomSwitchThreshhold) czoom = zoomSwitchThreshhold;
            gmap.setCenter(state.getBounds().getCenter(), czoom);
          });
        }
      } catch (e) {
        if (typeof console != 'undefined') console.log(e.message);
      }
      }
    );

    var overlay = new GGeoXml(kmlSource);

    return overlay;
  }

  return null;
}

//--------------------------------------------------------------------------------
function printMap(){
	var map_clone = $('#map_canvas');
	var params = mapParams();
	var qstring = 'z=' + params.z + '&clat=' + params.clat + '&clng=' + params.clng + '&addr=' + params.addr + '&city=' + params.city + '&state=' + params.state + '&zip=' + params.zip;
	print_window = window.open (printCoverageURL+'?'+qstring+'&coveragetype='+coveragetype, "print_window","location=0,status=0,width=620,height=770,scrollbars=1");
}
function showPrintMap(print_canvas){
	if (isBrowserIE()) {
		print_canvas.html($('#map_canvas').html());
	} else {
		var clone_map = document.getElementById('map_canvas').cloneNode(true);
		print_canvas.html(clone_map);
	}
}
//--------------------------------------------------------------------------------
function printWindow(){ print_window.print(); }

//--------------------------------------------------------------------------------
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}
function initMap() {
	gmap=new GMap2(document.getElementById("map_canvas"),{draggingCursor: 'move', draggableCursor: 'pointer'});
	gmap.enableScrollWheelZoom();
	gmap.enableDoubleClickZoom();
	gmap.enableContinuousZoom();
	gmap.addControl(new GLargeMapControl());

	GEvent.addListener(gmap, "zoomend", switchLayers);

	if (currentzipcode == '') {
  	var qstring = new String(document.location);
	//var qstring = ().toQueryParams();
  	qstring.clat = getQueryVariable('clat');
  	qstring.clng = getQueryVariable('clng');
  	qstring.z = getQueryVariable('z');
  	if (qstring.clat && qstring.clng && qstring.z) {
  		//map center params was passed through the querstring. so use them.
  		gmap.setCenter(new GLatLng(parseFloat(qstring.clat), parseFloat(qstring.clng)), parseInt(qstring.z));
  		if (qstring.mlat && qstring.mlng) {
  			//a lat/lon for a marker was specified, so show that too.
  			gmap.addOverlay(new GMarker(new GLatLng(parseFloat(qstring.mlat), parseFloat(qstring.mlng))));
  		}
  	} else {
  		//no map center params were passed in. so use default.
  		gmap.setCenter(initMapCenter, 4);
  	}
	}

	GEvent.addListener(gmap, "click", function(overlay, latlng) { if(isBrowserIE(6) && gmap.getZoom() < 5) { gmap.setCenter(latlng, 6); } });

	initFormFields(qstring);
	setLegend();

}
//--------------------------------------------------------------------------------
function wheelblock(e) {
	if (!e){ e = window.event }
	if (e.preventDefault){ e.preventDefault() }
	e.returnValue = false;
}

function getGeoCoder() {
	if (geocoder == null) {
		geocoder = new GClientGeocoder();
	}
	return geocoder;
}

function postSignup(formdata) {

	$('#coverageemailsignup').ajaxForm(
			{
				dataType: 'json',
				beforeSubmit: function(formData, jqForm, options) {
					if (ajaxBlocked($(jqForm).find('button'))) return false;
				},
				success: function(jsonres) {
					ajaxUnblock();
					if (jsonres.isSuccess) {
						if (searchInfoWin != null) {
							gmap.removeOverlay(searchInfoWin);
							searchInfoWin = null;
				    	}
			    		searchInfoWin = new CoverageMapsInfoWin(searchMarker.getLatLng(), jsonres.message);
			    		gmap.addOverlay(searchInfoWin);
					} else {
						$('#popupCoverageContainer').hide();
						var content = '<div align="left" style="padding: 5px 15px;"><h2 style="color: red; font-weight: bold">Signup Error</h2>';
						content = content + jsonres.message + '</div>';
						$('#popupCoverageContent').html(content);
						openPopUp();
					}
				}

			}
		);

}

//--------------------------------------------------------------------------------
function passMapParams(anchor) {
	var params = mapParams();
	anchor.href = anchor.href + '?z=' + params.z + '&clat=' + params.clat + '&clng=' + params.clng + '&addr=' + params.addr + '&city=' + params.city + '&state=' + params.state + '&zip=' + params.zip;
}

function mapParams() {
	var c = gmap.getCenter();
	var params = new Hash();
	params.z = gmap.getZoom();
	params.clat = c.lat();
	params.clng = c.lng();
	params.addr = $('#address').val();
	params.city = $('#city').val();
	params.state = $('#cm_state').val();
	params.zip = $('#zip').val();
	return params;
}

function initFormFields(qstring) {
	if (qstring) {
		if (qstring.addr) $('#address').val(qstring.addr);
		if (qstring.city) $('#city').val(qstring.city);
		if (qstring.state) $('#cm_state').val(qstring.state);
		if (qstring.zip) $('#zip').val(qstring.zip);
	}
}

//--------------------------------------------------------------------------------
function showFAQ(num, top) {
	if(top === undefined) {
		var FAQ_ans = $('#faq_ans_'+num);
		if(FAQ_ans.style.display == "none") {
			Effect.SlideDown(FAQ_ans, {
				duration: 0.3
			});
		} else {
			Effect.SlideUp(FAQ_ans, {
				duration: 0.3
			});
		}
	} else {
		$('#popupCoverageContainer').hide();
		var content = '<div align="left" style="padding: 5px 15px;"><h3>' +$('#top_faq_'+num).innerHTML+ '</h3>';
		content = content + $('#top_faq_ans_'+num).innerHTML +'</div>';
		$('#popupCoverageContent').html(content);
		openPopUp();
	}
}

//--------------------------------------------------------------------------------
function searchErrorPopup() {
	$('#popupCoverageContainer').hide();
	var content = '<div align="left" style="padding: 5px 15px;"><h3 style="font-size: 14pt; font-weight: bold; color: #964d09;">We cannot find that address.</h3>';
	content = content + '<p>Please double check the address, or try entering just the city and state, or ZIP code.</p></div>';
	$('#popupCoverageContent').html(content);
	openPopUp();
}

//--------------------------------------------------------------------------------
function openPopUp(maps) {
	// RESET WIDTH AND STYLES
	if(maps == 'fancypopup') {
		$('#popupCoverageContainer').css({'width' : '250px'});
		$('#popupCoverageContent').css({'margin':'0'});
	} else {
		$('#popupCoverageContainer').css({'width' : '500px'});
		$('#popupCoverageContent').css({'margin':'40px 35px'});
		$('#closeBtn').css({'display' : 'block','visibility' : 'visible'});
		$('#popupshadow').css({'display' : 'block','visibility' : 'visible'});
	}


	// HIDE SHADOW FOR IE6 MAPS VIEW
	var popupshadowsrc = $('#popupshadow').attr('src');
	var popupshadowtypearr = popupshadowsrc.split("popup_shadow.");
	var popupshadowtype = popupshadowtypearr[1];
	var isIE6 = false;
	if(popupshadowtype == "gif") {
		isIE6 = true;
		var popupheight = $('#popupCoverageContainer').height();
		$('#popupshadow').css({'height' : popupheight+"px"});
	}
	var popupwidth = $('#popupCoverageContainer').width();
	var popupheight = $('#popupCoverageContainer').height();
	var leftoffset = (786 - popupwidth)/2;



	if(leftoffset <= 0) {
		leftoffset = 0;
	}
	if(maps !== undefined) {
		$('#closeBtn').css({'display' : 'none','visibility' : 'hidden'});
		if(isIE6 == true) {
			$('#popupCoverageContainer').css({'width': (imgwidth-50)+'px'});
			$('#popupshadow').css({'display' : 'none','visibility' : 'hidden'});
		}
	}
	if(maps == 'fancypopup') {
		$('#closeBtn').css({'display' : 'none'});
		$('#popupshadow').css({'display' : 'none'});
	}

	var closebtnxoffset = Math.round((popupheight * 0.05)+ 5) + "px";
	var closebtnyoffset = Math.round((popupwidth - 786) * 0.15) + "px";
	if(closebtnxoffset < 5) { closebtnxoffset = 0; }
	if(closebtnyoffset < 5) { closebtnyoffset = 0; }
	$('#closeBtn').css({'top' : closebtnxoffset});
	$('#closeBtn').css({'left' : closebtnyoffset});
	$('#popupCoverageContainer').css({'left' : leftoffset + "px"});
	$('#popupCoverageContainer').show("slow");
}
function closePopUp() {
	$('#popupCoverageContainer').hide();
}

//--------------------------------------------------------------------------------
function CoverageMapsInfoWin(latlng, html) {
	this.latlng_ = latlng;
	this.html_ = html;
	this.prototype = new GOverlay();

	// Creates the DIV representing the infowindow
	this.initialize = function(map) {
		var div = $('<div />');

		this.map_ = map;
		this.div_ = div;

		div.css({
			'position' : 'absolute',
			'width' : '247px'
		});
		div.addClass('cminfowin');
		div.addClass('noprint');

		$(map.getPane(G_MAP_FLOAT_PANE)).append(div);

		this.html(html);
	};

	this.html = function(html){
		this.html_ = html;

		this.div_.html('');

		var topdiv = $('<div />');
		topdiv.css({
			'background-image' : 'url(/images/popup/infowin-top.png)',
			'background-repeat': 'no-repeat',
			'height' : '13px',
			'padding': '0 0 0 0',
			'textAlign': 'right',
			'width': '247px'
		});
		topdiv.addClass('cmtopdiv');

		this.div_.prepend(topdiv);

		var content = $('<div />');
		content.addClass('infowin-content');
		content.css({
			'background-image' : 'url(/images/popup/infowin-middle.png)',
			'background-repeat': 'repeat-y',
			'position' : 'relative',
			'overflow' : 'hidden',
			'width' : '247px',
			'padding': '0 0 0 0'
		});

		var contentleft = $('<div />');
		contentleft.css({
			'width': '210px',
			'float': 'left',
			'margin': '0 0 0 12px'
		});
		contentleft.html(html);
		content.append(contentleft);

		var contentright = $('<div />');
		contentright.css({
			'width': '15px',
			'float': 'left',
			'padding': '0 0 0 0'
		});
		var closer = $('<a />');
		closer.html('<img style="display: block; float: right; width: 15px; height: 15px;" src="/images/popup/infowin-close.gif" width="15" height="15" border="0" />');
		closer.bind('click', {thisContext: this}, function(eventData) {
			eventData.data.thisContext.closewin(eventData);
		});
		contentright.prepend(closer);

		content.append(contentright);

		var cleardiv = $('<a />');
		cleardiv.css({
			'clear': 'left'
		});
		content.append(cleardiv);

		topdiv.after(content);

		var bottomdiv = $('<div />');
		bottomdiv.css({
			'background-image' : 'url(/images/popup/infowin-bottom.png)',
			'background-position' : 'bottom',
			'width' : '247px',
			'height' : '39px'
		});
		bottomdiv.addClass('cmbottomdiv');

		content.after(bottomdiv);

		this.redraw(true);
	};

	// Remove the main DIV from the map pane
	this.remove = function() {
	  this.div_.remove();
	};

	// Copy our data to a new instance
	this.copy = function() {
	  return new CoverageMapsInfoWin(this.latlng_, this.html_);
	};

	// Redraw based on the current projection and zoom level
	this.redraw = function(force) {
		if (!force) return;

		var point = this.map_.fromLatLngToDivPixel(this.latlng_);

		// Now position our DIV based on the DIV coordinates of our bounds

		this.div_.css({
			'left' : (point.x - 46)+'px',
			'top' : (point.y - this.div_.height() + 7) + 'px'
		});
	};

	this.closewin = function(evt) {
		try {
			this.map_.removeOverlay(this);
			if (this.map_.getZoom() <= zoomSwitchThreshhold - 1) {
				if (searchMarker != null) {
					//only hide the search marker if the user
					//is in the state contour view.
					//otherwise leave it so the user
					//use for refrence as they zoom in.
					gmap.removeOverlay(searchMarker);
					searchMarker = null;
				}
			}
			searchInfoWin = null;
			evt.stop();
		} catch (e) {
			//alert(e.message);
		}
	};
}

//--------------------------------------------------------------------------------
function placeSearchMarker(geopoint) {
    if (searchMarker != null) {
		gmap.removeOverlay(searchMarker);
		searchMarker = null;
    }
	var coverageGIcon = new GIcon(G_DEFAULT_ICON, '/images/popup/infowin-dot.png');
	coverageGIcon.iconSize = new GSize(17, 17);
	coverageGIcon.shadow = '';
	coverageGIcon.iconAnchor = new GPoint(7,7);
	coverageGIcon.infoWindowAnchor = new GPoint(7,7);

	searchMarker = new GMarker(geopoint, {icon: coverageGIcon});

	gmap.addOverlay(searchMarker);
}

//--------------------------------------------------------------------------------
function clearSearchInfoWin() {
	if (searchInfoWin != null) {
		gmap.removeOverlay(searchInfoWin);
		searchInfoWin = null;
	}
	if (searchMarker != null) {
		gmap.removeOverlay(searchMarker);
		searchMarker = null;
	}
}

function showSearchInfoWin(latlng, msg) {

	getGeoCoder().getLocations(
			latlng,
			function(geores) {
				var txtres = '';
				if (geores.Status.code == 200) {
					var sparams = '';
					if ($.trim($('#address').val()) == '' && $.trim($('#city').val()) == '' && $.trim($('#zip').val()) == '') {
						//state only search
						sparams = $('#cm_state').val();
					} else {
						var placemark = null;
						var matchedname = false;
						//Get the most accurate placemark
						$(geores.Placemark).each( function()  {
							if (placemark == null) {
								placemark = this;
							} else if (this.AddressDetails.Accuracy > placemark.AddressDetails.Accuracy) {
								placemark = this;
							}
						});
						var addrparts = placemark.address.split(',');
						var statezip = ($.trim(addrparts[addrparts.length-2])).split(' ');
						var state = statezip[0];
						var zip = statezip[1];
						var city =  $.trim(addrparts[addrparts.length-3]);

						sparams += ($.trim($('#address').val()) != '' ? ($.trim($('#address').val()) + ', ') : ''); //address
						sparams += city + ', '; //city
						sparams += state + ' '; //state
						sparams += zip; //zip

						$('#zip').val(zip);
						$('#city').val(city);
						$('#cm_state').val((''+state).toUpperCase());
					}
					txtres = msg.replace('#{address}', sparams);
				} else {
					var sparams = ($('#address').val() != '' ? $('#address').val() + '<br />': '');
					sparams += ($('#city').val() != '' ? $('#city').val() + ', ' : '');
					sparams += ($('#cm_state').val() != '' ? $('#cm_state').val() + ' ': '');
					sparams += ($('#zip').val() != '' ? $('#zip').val() : '');
					txtres = template.evaluate( {address: sparams} );
				}

				if (searchInfoWin != null) {
					gmap.removeOverlay(searchInfoWin);
					searchInfoWin = null;
				}

				searchInfoWin = new CoverageMapsInfoWin(latlng, txtres);
				gmap.addOverlay(searchInfoWin);

				if ($('#coverageemailsignup').length > 0) {
					$('#signupzip').val($('#zip').val());

					$('#signupfname').mousedown(
							function(event) {
								event.stopPropagation();
							}
					);
					$('#signupemail').mousedown(
							function(event) {
								event.stopPropagation();
							}
					);
					$('#signupzip').mousedown(
							function(event) {
								event.stopPropagation();
							}
					);
					/*
					$('#signupsubmit').mousedown(
							function(event) {
								event.stopPropagation();
							}
					);
					*/
					$('#signupfname').focus();

					postSignup();
				}
			}
	);

}

//--------------------------------------------------------------------------------
// FORM HANDLER
//--------------------------------------------------------------------------------
function getLocation(){
	if ($.trim($('#address').val()) == '' && $.trim($('#city').val()) == '' && $.trim($('#cm_state').val()) == '' && $.trim($('#zip').val()) == '') return;

	var address = $.trim($('#address').val()) + "+" + $.trim($('#city').val()) + "+" + $.trim($('#cm_state').val()) + "+" + $.trim($('#zip').val()) + "+USA";

	getGeoCoder().getLatLng(address, function(latlng) {
		coverageSearchButton = $('#coveragesearch').html();
		$('#coveragesearch').html(spinnerCode);
		if (!latlng) {
			$('#coveragesearch').html(coverageSearchButton);
			searchErrorPopup();
		} else {
			$('#popupCoverageContainer').hide();
			//location found
			getLocationNear(latlng);

		}
	});
}

//--------------------------------------------------------------------------------
function getLocationNear(geopoint) {
	var params = new Hash();
    params.coveragetype = coveragetype;
    if(isorphanpage) {
    	params.isorphanpage = 'true';
    } else {
    	params.isorphanpage = 'false';
    }

    var searchservice = '';
    var zoom = 4;
    if ($.trim($('#address').val()) == '' && $.trim($('#city').val()) == '' && $.trim($('#zip').val()) == '') {
        //only the state was specified. so search by state.
    	searchservice = serviceFindByState;
		params.state = $('#cm_state').val();
		zoom = 6;
    } else {
        //search by point
    	searchservice = serviceFindByPoint;
        params.lat = geopoint.lat();
        params.lng = geopoint.lng();
        zoom = 13;
    }

    $.ajax(
    	{
    		type: 'POST',
    		url: searchservice,
    		dataType: 'json',
    		data: params,
	    	success: function (coverageresult) {
            		try {
            			//alert(coverageresult);
			    		//var txtres = res.responseText;
						//var coverageresult = txtres.evalJSON();
						var center = geopoint;

						var boundingbox = coverageresult.result;
						if (boundingbox) {
							var centroid = boundingbox.centroid;
							var vertices = boundingbox.vertices;

							if (vertices) {
								var sw = new GLatLng(parseFloat(vertices[0].lat), parseFloat(vertices[0].lng));
								var ne = new GLatLng(parseFloat(vertices[2].lat), parseFloat(vertices[2].lng));
								zoom = gmap.getBoundsZoomLevel(new GLatLngBounds(sw, ne));
							}
							//center = new GLatLng(parseFloat(centroid.lat), parseFloat(centroid.lng));
						}

						if (coverageresult.type == 'POINT_SEARCH') {
							clearSearchInfoWin();

							if(($.trim($('#address').val()) != "")&&($.trim($('#city').val()) != "")) {
								gmap.setCenter(center, 13);
								placeSearchMarker(geopoint);
								if (coverageresult.success || coverageresult.message) {
									showSearchInfoWin(geopoint, coverageresult.message);
								}
							} else if(currentzipcode != '' && isShopZip && !isInitialShopZipPopupShown) {
								//Show the 'you are viewing coverage for xxxx' if the user comes
								//to this page if the currentzipcode was obtained from their shop zip.
								//On show this once on initial page load.
								gmap.setCenter(center, zoom);
								$('#popupCoverageContainer').hide();
								var newcontent = '<div align="left" style="padding: 5px 15px;">' +$('#currentmarketcopy').html()+ '</div>';
								$('#popupCoverageContent').html(newcontent);
								openPopUp('fancypopup');
								isInitialShopZipPopupShown = true;
							} else {
								gmap.setCenter(center, zoom);
							}

						} else {
							//Search by state. Don't show any info windows, just show coverage
							//at the state.
							clearSearchInfoWin();
							if (!coverageresult.success && !boundingbox) zoom = 7;
							zoomendReCenter = false;
							gmap.setCenter(center, zoom);
						}
            		} catch (e) {
            			//alert(e);
            		}
            		$('#coveragesearch').html(coverageSearchButton);
	    		}
    	} );


}
function setZip(btn) {
	var currentzipcode = $('#zip').val();
	$.ajax({
		type: "POST",
		url: setZipUrl,
		data: "zip="+currentzipcode,
		success: function(){
			window.location = btn.href;
			return true;
		}
	});
	return false;
}