$(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.doSearch($.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.doSearch = function() {
	 	var query = $.trim($('#myLocation', container).val());
	 	if (query.match(/^\d{4}$/)) {
			self.findByStoreNum(query);
		}
		else {
			self.findByLocation(query);
		}
	}
	
		
	/**
	  * Find By Address or Postal Code
	  */
	this.findByLocation = 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=5&express=';
				// 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.set_content('<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 = '';
				
				// add store to listing
				var distance = (store.distance != null ? distance = Math.round(store.distance * 100) / 100 : 0).toString();
				
				var address = '<p><strong>' + store.store_name + '</strong>,<br/>' +
							  store.address + '<br/>' +
							  store.city + ', ' + store.province + '<br />' + store.postal_code + '<br/>';
				if (store.phone != '') {
					address += 'T&eacute;l&eacute;phone : ' + store.phone + '<br/>';
				}
				if (store.delivery == 'Y'){
					address += 'Livraison : ';
					if(store.delivery_phone_number != ''){
						address += ' ' + store.delivery_phone_number;
					}
					address += '<br/>';
				}				
				
				if (store.mon_open != ''){
					storeHours += 'Lundi : ' + replaceStr(replaceStr(store.mon_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.mon_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.mon_close),':',' h '),'PM','') + '<br/>';
				}
				
				if (store.tue_open != ''){
					storeHours += 'Mardi : ' + replaceStr(replaceStr(store.tue_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.tue_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.tue_close),':',' h '),'PM','') + '<br/>';
				}				

				if (store.wed_open != ''){
					storeHours += 'Mercredi : ' + replaceStr(replaceStr(store.wed_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.wed_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.wed_close),':',' h '),'PM','') + '<br/>';
				}

				if (store.thur_open != ''){
					storeHours += 'Jeudi : ' + replaceStr(replaceStr(store.thur_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.thur_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.thur_close),':',' h '),'PM','') + '<br/>';
				}

				if (store.fri_open != ''){
					storeHours += 'Vendredi : ' + replaceStr(replaceStr(store.fri_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.fri_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.fri_close),':',' h '),'PM','') + '<br/>';
				}

				if (store.sat_open != ''){
					storeHours += 'Samedi : ' + replaceStr(replaceStr(store.sat_open,':',' h '),'AM','') + ' &agrave; ';
				}
				if (store.sat_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.sat_close),':',' h '),'PM','') + '<br/>';
				}
				
				if (store.sun_open != ''){
					storeHours += 'Dimanche : ' + replaceStr(replaceStr(replaceStr(store.sun_open,':',' h '),'AM',''),'PM','') + ' &agrave; ';
				}
				if (store.sun_close != ''){
					storeHours += replaceStr(replaceStr(frenchHours(store.sun_close),':',' h '),'PM','') + '<br/>';
				}
				
				
				var infoWindowContent = '<p>' + address + '</p><p>' + storeHours + '</p>';
				self.plotLetteredMarker(latlng, letter, infoWindowContent);	
				
				bounds.extend(latlng);						
				
				var instoreServices = '';
				if (store.delivery == 'Y'){
					instoreServices += 'Livraison<br/>';
				}
				if (store.catering == 'Y'){
					instoreServices += 'Traiteur<br/>';
				}
				if (store.late_night == 'Y'){
					instoreServices += 'Ouvert tard le soir<br/>';
				}
				if (store.pick_up == 'Y'){
					instoreServices += 'Pour emporter<br/>';
				}
				if (store.dine_in == 'Y'){
					instoreServices += 'Salle &agrave; manger<br/>';
				}
				if (store.drive_thru == 'Y'){
					instoreServices += 'Service au volant<br/>';
				}
				if (store.express == 'Y'){
					instoreServices += 'Comptoir Express<br/>';
				}
				if (store.parking_available == 'Y'){
					instoreServices += 'Parking Available<br/>';
				}
				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.replace('.',',') + ' 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();
			
			
			if (stores.length > 1) {
				self.map.fitBounds(bounds);
			}
			else {
				self.map.setCenter(bounds.getCenter());
				self.map.setZoom(15);
			}
		}
		else {
			// search by proximity
		}			
	}
}
function getKFCStoreResults(address){
	//StoreLocator.doSearch();
	StoreLocator.doSearch(address);
}

function replaceStr(str, strToFind, strReplaceWith){
   var newString = str.toString();
   return newString.replace(strToFind, strReplaceWith);
}

function frenchHours(str){
   var strOrig = str.toString();
   var hours = strOrig.substring(0,strOrig.indexOf(':'));
   if(hours=='1' || hours=='2' || hours=='3'){
   	var newHours = '0'+hours;
   }else{
   	var newHours = +(hours) + 12;
   }
   //alert(newHours);
   newHours = newHours+strOrig.substring(strOrig.indexOf(':'), strOrig.indexOf(':')+3);
   //alert(newHours);
   return newHours;
}
function getKFCStoreResults(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.doSearch(address);
}
/*
function getKFCStoreResults(address){
	$('#pagewrapper').show();
	StoreLocator.initialize();
	$('#myLocation').val(address);
	StoreLocator.doSearch(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);
}