$(document).ready(function() {
	StoreLocator.initialize();
	$('.searchTerms').eq(0).blur()
	$('#myLocation').focus();
});

var StoreLocator = new function() {
	var self = this;
	var container = $('#pagewrapper');
	this.map = null;
	this.baseIcon = null;
	this.letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	this.markers = [];
	
	/**
	  * Initialize the store locator widget
	  */
	this.initialize = function() {
		var mapOptions = { 
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
			// zoom out to show all of Canada
			center: new google.maps.LatLng(53.74871079689897, -93.515625),
			zoom: 3
		};
		
		// if service is available, zoom in on user's current location
		if (google.loader.ClientLocation != null) {
			mapOptions.center = new google.maps.LatLng( google.loader.ClientLocation.latitude,  google.loader.ClientLocation.longitude);
			mapOptions.zoom = 8;
		}
		self.map = new google.maps.Map(document.getElementById('map'), mapOptions);
		self.geocoder = new google.maps.Geocoder();
		$('#myLocation', container).focus(function() {
			$('body').keypress(function(e) {
				if (e.keyCode == 13) {
					self.doSearchMainSite($.trim($('#myLocation', container).val()));
					return false
				}
			});
		}).blur(function() {
			$('body').unbind('keypress');
		});
		
		$('.btnSearch', container).click(self.doSearch);
		
		if ($('.findStores').length > 0) {
			$('.findStores').click(function() {
				generateCover();
				var renderContent = function(html) {
					var popup = generatePopup(819, 500, 'chooseAddress', 'large');
					popup
						.find('.container').prepend(html.children())
						.find('.btnSelect').attr('href', '#');
					
					$('.btnClose', popup).click(closePopup);
					
					var canada = 'Canada';
					$('.address', popup).each(function() {
						if ($('.country', this).text()!= canada) {
							$('.btnSelect', this).hide();
						}
					});
					
					$('.btnSelect').click(function() {
						var postalCode = $('.postalCode', $(this).siblings('.addressWrapper')).text();						
						self.findByLocation(postalCode);
						$('#storeLocator #myLocation').val(postalCode);
					});
					
					var height = popup.height();							
					var x = getXCoordinate(819);
					var y = getYCoordinate(height);
					animatePopup(popup, 819, height, x, y, 300);
				}
			
				var addressBookUrl = '/stores/shop/AddressBookForm?catalogId=' + catalogId + '&langId=' + langId + '&storeId=' + storeId + '&mode=selectBillingAddress&ajax=true';
				$.ajax({
					url: addressBookUrl,
					type: 'GET',
					dataType: 'html',
					success: function(html) {
						var html = $(html);
						renderContent(html);
					}
				});
			});
		}
	}
	
	
	/**
	  *
	  */
	this.doSearchMainSite = function() {
		var query = $.trim($('#myLocation', container).val());
		document.getElementById('locations').style.visibility="visible";
	 	self.findByLocationMainSite(query);
	}
	
	
	/**
	  * Find By Address or Postal Code for KFC.ca
	  */
	this.findByLocationMainSite = function(address) {
		//if ();
		self.clearMarkers();
		self.geocoder.geocode({address: address}, function(results, status) {
			//window.geocoderResults = results;
			if (results.length > 0) {
				var latlng = results[0].geometry.location;
				var formattedAddress = results[0].formatted_address;
				self.map.setCenter(latlng);
				self.map.setZoom(9);
				var url = '/kfclocator/locator?langId=1&latitude=' + latlng.lat() + '&longitude=' + latlng.lng() + '&services=&limit=10&express=yes';
				// if selecting an address from address book popup
				if ($('body .popup').length > 0) {
					$('.popup .btnClose').click();
				}
				$.getJSON(url, displayResults);				
			}
			else {
				alert('Invalid entry.  Please try again');
			}
		});
	}	
	
	/**
	  * Find By Store Number
	  */
	this.findByStoreNum = function(storeNum) {
		self.clearMarkers();
		var url = '/stores/shop/StoreLocator?langId=1&storeId=10051&catalogId=10001&storeNum=' + storeNum;
		$.getJSON(url, function(stores) {
			if (stores.length > 0) {
				displayResults(stores);
			}
			else {
				//alert('Pick-up location ' + storeNum + ' is not a number. Please re-enter the unit number a try again');
				alert(eStore.storeText.storelocator.store_not_found.replace(/\{\?\}/, storeNum));
			}
		});
	}
	
	// Creates a marker whose info window displays the letter corresponding
	// to the given index.
	this.plotLetteredMarker = function(latlng, letter, infoWindowContent) {
		var iconImg = "images/marker" + letter + ".png";		
		var shadowImg = "images/shadow.png";
		var shadowAnchor = new google.maps.Point(10, 34);
		var shadow = new google.maps.MarkerImage(shadowImg, null, null, shadowAnchor);
		
		var marker = new google.maps.Marker({
			position: latlng,
			icon: iconImg,
			shadow: shadow,
			map: self.map
		});
		
		google.maps.event.addListener(marker, 'click', function() {
			var infoWindow = new google.maps.InfoWindow({
				pixelOffset: new google.maps.Size(0, 34),
				maxWidth: 200
			});
			infoWindow.setContent('<div class="storeInfoWindow">' + infoWindowContent + '</div>');
			infoWindow.open(self.map, marker);
		});
		
		self.markers.push(marker);
	}
	
	this.clearMarkers = function() {
		for (var i = 0; i < self.markers.length; i++) {
			self.markers[i].setMap(null);
		}
		self.markers = [];
	}
	
	var displayResults = function(stores) {
		var bounds = new google.maps.LatLngBounds();
		if (stores.length > 0) {
			$('#locations .stores', self.container).empty();
			for (var i = 0; i < stores.length; i++) {
				var store = stores[i];
				var letter = String.fromCharCode("A".charCodeAt(0) + i);
				//var latlng = new google.maps.LatLng(store.latitude, store.longitude);
				var latlng = new google.maps.LatLng(Number(store.latitude), Number(store.longitude));
				var storeHours = '';
				
				var sColonelsClub_Key='<b></b>';
				var sName=store.store_name;
				var isColonelsClub=0;
				if (sName.indexOf(sColonelsClub_Key)>0)
				{
					isColonelsClub=1;
					sName=sName.replace(sColonelsClub_Key,'');
				}
				
				// add store to listing
				var distance = (store.distance != null ? distance = Math.round(store.distance * 100) / 100 : 0);
				
				var address = '<p><strong>' + sName + '</strong>,<br/>' +
							  store.address + '<br/>' +
							  store.city + ', ' + store.province + '<br/>' + store.postal_code + '<br/>';
				if (store.phone != '') {
					address += 'Phone: ' + store.phone + '<br/>';
				}

				if (store.delivery == 'Y'){
					address += 'Delivery: ';
					if(store.delivery_phone_number != ''){
						address += ' ' + store.delivery_phone_number;
					}
					address += '<br/>';
				}				
				
				if (store.mon_open != ''){
					storeHours += 'Monday: ' + store.mon_open + '-';
				}
				if (store.mon_close != ''){
					storeHours += store.mon_close + '<br/>';
				}
				
				if (store.tue_open != ''){
					storeHours += 'Tuesday: ' + store.tue_open + '-';
				}
				if (store.tue_close != ''){
					storeHours += store.tue_close + '<br/>';
				}				

				if (store.wed_open != ''){
					storeHours += 'Wednesday: ' + store.wed_open + '-';
				}
				if (store.wed_close != ''){
					storeHours += store.wed_close + '<br/>';
				}

				if (store.thur_open != ''){
					storeHours += 'Thursday: ' + store.thur_open + '-';
				}
				if (store.thur_close != ''){
					storeHours += store.thur_close + '<br/>';
				}

				if (store.fri_open != ''){
					storeHours += 'Friday: ' + store.fri_open + '-';
				}
				if (store.fri_close != ''){
					storeHours += store.fri_close + '<br/>';
				}

				if (store.sat_open != ''){
					storeHours += 'Saturday: ' + store.sat_open + '-';
				}
				if (store.sat_close != ''){
					storeHours += store.sat_close + '<br/>';
				}
				
				if (store.sun_open != ''){
					storeHours += 'Sunday: ' + store.sun_open + '-';
				}
				if (store.sun_close != ''){
					storeHours += store.sun_close + '<br/>';
				}
				
				
				var infoWindowContent = '<p>' + address + '</p><p>' + storeHours + '</p>';
				self.plotLetteredMarker(latlng, letter, infoWindowContent);	
				
				bounds.extend(latlng);						
				
				var instoreServices = '';
				if (store.delivery == 'Y'){
					instoreServices += 'Home Delivery<br/>';
				}
				if (store.catering == 'Y'){
					instoreServices += 'Catering<br/>';
				}
				if (store.late_night == 'Y'){
					instoreServices += 'Late night<br/>';
				}
				if (store.drive_thru == 'Y'){
					instoreServices += 'Drive-thru<br/>';
				}
				if (store.express == 'Y'){
					instoreServices += 'Express<br/>';
				}
				if (store.parking_available == 'Y'){
					instoreServices += 'Parking Available<br/>';
				}
				if (store.dine_in == 'Y'){
					instoreServices += 'Dine In<br/>';
				}
				if (store.pick_up == 'Y'){
					instoreServices += 'Pick Up<br/>';
				}

				if (isColonelsClub == 1){
					instoreServices += '<img src="images/colonels_club.jpg" border="0" height="30" /> ';
				}
				
				if (store.pizza_hut == 'Y'){
					instoreServices += '<img src="images/pizzahut.jpg" border="0" width="29" height="30" /> ';
				}
				if (store.taco_bell == 'Y'){
					instoreServices += '<img src="images/tacobell.jpg" border="0" width="29" height="30" /><br/>';
				}else{
					instoreServices += '<br/>';
				}
				var storeInfo = $('<tr class="store">' +
									'<td class="storeDistance" align="center">' +
										//(storeTypes[store.store_type] ? '<p>' + storeTypes[store.store_type] + '<br/>' : '') +
										'<img class="marker" src="images/marker' + letter + '.png" style="margin-bottom: 5px;"  />' +
										(distance > 0 ? '<br/>' + distance + ' km' : '') +
									'</td>' +
									'<td class="storeInfo"><p>' +
										address +
									'<br/></p></td>' +
									'<td class="storeHours"><p>' +
										storeHours +
									'</p></td>' +
									'<td class="storeOptions"><p>' +
										instoreServices +
									'</p></td>' +
								  '</tr>');
								  
				$('#locations .stores', self.container).append(storeInfo);
				
			}
			
			$('.locations').show();
			document.getElementById('kfclocationstitle').style.visibility='visible';
			
			document.getElementById('searchlegend').style.visibility='visible';
			
			if (stores.length > 1) {
				self.map.fitBounds(bounds);
			}
			else {
				self.map.setCenter(bounds.getCenter());
				self.map.setZoom(15);
			}
		}
		else {
			// search by proximity
		}			
	}
}

function getKFCStoreResultsMainSite(address){
	$('#pagewrapper').show();
	StoreLocator.initialize();
	if(validPCodeNoSpace(address)){
		//got a valid postal code with no space..some postal codes need that space
		//for some reason...so let's add it
		address = address.substring(0,3) + " " + address.substring(3,6);
	}
	$('#myLocation').val(address);
	StoreLocator.doSearchMainSite(address);
}

function hideStoreLocator() {
	$('#pagewrapper').hide();
}
function validPCodeNoSpace(address) {
   var zipRegExp = /(^\D{1}\d{1}\D{1}\d{1}\D{1}\d{1}$)/;
   return zipRegExp.test(address);
}
