(function(){
	var $ = jQuery,
		site = window.site = {};
	
	site.paths = {};
	site.paths.root = window.location.protocol+"//"+window.location.host+"/";
	site.paths.theme = "/themes/site_themes/default_site/";

	site.paths.segments = (window.location.pathname).replace(/(\/$)/,"").split(/\/+/);
	
	
	site.pages = {};
	
	
	
	site.pages["common"] = new esf.site.Page({
		test:function(){return false;}, //to hardset a page to display, redefine this to "true". See embeds/footer_assets template.
		init:function(){
			var P = this;
			P.prepSubNav();
			P.createSlideshows(".slideshow");
			P.createAlphaSegmentFilters("select.select-alpha-uri");
			P.createMaps(".wrap-map .canvas",".directory-index .vcard");
			
			
			$("#siteDialog").dialog({autoOpen:false});
			
			$("a[data-post]").anchorPost();
			
			//Add home page to the breadcrumb
			var breadcrumbs = $("#breadcrumbs");
			breadcrumbs.find("li:first").each(function(){
				$(this).before("<li><a href='/'>Home</a></li>");
			});
			
			//Create accordions
			$("#sitePage .ui-accordion").each(function(){
				var acc = $(this),
					admin = acc.children(".admin-actions").remove();	
				
				acc.accordion({collapsible:true, active:false, clearStyle:true});
				//sbar.addClass("ui-accordion ui-widget ui-accordion-icons ui-helper-reset");
				//sbar.children(".admin-actions").remove();
				//title.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top");
				//content.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active");
				
				//title.click(function(){
				//	sbar.children("div:last").slideToggle();
				//});
			});
			
			
			if($.browser.msie){
				var fontsLink = $("link[href$='fonts.css']"),
					fontsLinkAnchor = fontsLink.prev(); //Store placement of stylesheet references so we don't break the stack
					
				//Remove the fonts CSS before IE print
				$(window).bind("beforeprint", function(){
					fontsLink.remove();
				});
				//Add the font CSS after IE print
				$(window).bind("afterprint", function(){
					fontsLinkAnchor.after(fontsLink);
				});
			}
			/*
			if($.browser.msie){
				var pied;
				//Before print
				$(window).bind("beforeprint", function(){
					//Loop through every element, and remove/store behavior CSS property where found.
					pied = [];					
					$("*").each(function(){
						var $this = $(this),
							b = $this.css("behavior");
						if(b.length && b != "none"){
							$this.data("behavior", b);
							$this.css("behavior", "none");							
							pied.push(this);
						}
					});
				});
				//After print
				$(window).bind("afterprint", function(){
					//Loop through previously stored elements with behavior and restore property.
					$(pied).each(function(){
						var $this = $(this);
						$this.css("behavior", $this.data("behavior"));
					});
				});
			}*/
			
			P.prepAdminActions();
			
			
			//Create placeholders in textboxes
			$("input[placeholder]").placeholder();
			
			//Setup overlays/lightboxes			
			$("a[rel='enlarge']").each(function(){
				var $a = $(this),
					$zoomTip = $("<span class='tip'>Enlarge</span>").appendTo($a);				
			}).colorbox({transition:"none"});
		},
		
		prepSubNav:function(){
			var subNav = $("#siteSubNav");
			//Make all non-linked items use their first child's url, or their nearest parent's.
			subNav.find("li").not(":has(>a:first-child)").each(function(l, li){
				var $li = $(li),
					label = $li.contents().first().remove().text(),
					link = $li.find("a[href]:first");
					
				if(!link.length){
					link = $li.closest("li").find("a[href]:first");
				}
				
				link.clone().prependTo($li).empty().text(label);
			});
		},
		
		createSlideshows:function(selector){			
			if(!(selector instanceof $)) selector = $(selector);
			
			selector.each(function(){
				
				var div = $(".slideshow"),
					ulBanners = div.children("ul.banners"),
					ulControls = div.children("ul.controls");
				
				var sequence = new esf.widget.DisplaySequence({
					ul: ulBanners,
					displayTime: 6000,
					autoPlay:true
				});
				//ulControls.css({display:"block"});
				var controlBar = new esf.widget.DisplaySequenceControlBar({
					sequence: sequence,
					ul: ulControls,
					btnPlay: ulControls.children("li.item-play").addClass(this.activeClass),
					btnPause: ulControls.children("li.item-pause")
				});
			});			
			
		},
		
		createAlphaSegmentFilters:function(selects){
			var P = this;
			if(!(selects instanceof $)) selects = $(selects);
			selects.each(function(s, select){
				var $select = $(select);
				$select.change(function(evt){
					var path = window.location.pathname,
						letter = $select.val().toLowerCase();
					if((/\/alpha\/[a-z]/i).test(path)){
						path = path.replace(/(\/alpha)\/[a-z]/i, "$1/"+letter);
					}else{
						path = path.replace(/(\/alpha)?\/?$/, "/alpha/"+letter);	
					}
					window.location.pathname=path;
				});
			});
			
			return this;
		},
		
		createMaps:function(canvases, listings){
			if(!(canvases instanceof $)) canvases = $(canvases);
			if(!(listings instanceof $)) listings = $(listings);
			var P = this;
			canvases.each(function(c, canvas){
				var $canvas = $(canvas),
					center = $canvas.attr("data-center"),
					zoom = $canvas.attr("data-zoom");
					
					P.initMapControls($canvas.siblings(".controls"));
					
					if (center == null || !(/((\+|\-)?\d+(,\s)?){2}/).test(center)){
						center = new google.maps.LatLng(29.748594011243355, -95.46264606094358);
					} else { 
						center = center.split(/,\s?/);
						center = new google.maps.LatLng(center[0], center[1]); 
					}
					if (zoom == null || isNaN(parseInt(zoom))) {
						zoom = 15;
					} else {
						zoom = parseInt(zoom);
					}
					
					var map = P.map = new google.maps.Map(
						canvas,
						{
							center: center,
			
							mapTypeId: google.maps.MapTypeId.ROADMAP,
							mapTypeControl: false,
							mapTypeControlOptions: {
								style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
								//style:google.maps.MapTypeControlStyle.HORIZONTAL_BAR
							},
			
							navigationControl: false,
							navigationControlOptions: {
								//style: google.maps.NavigationControlStyle.SMALL
								style:google.maps.NavigationControlStyle.ZOOM_PAN
							},
			
							scaleControl: false,
							scaleControlOptions: {
							//style:google.maps.ScaleControlStyle.
							},
			
							scrollWheel: false,
							
							streetViewControl: false,
							
							zoom: zoom
			
					});
			
					new tbelt.gmaps.MarkerHandler(map);
					
					$canvas.data("gmap", map);
					
					//Create the dialog for info windows
					var dialog = $canvas.siblings(".dialog").dialog({autoOpen:false, resizable:false, dialogClass:"map-dialog", hide:"fade"});			
					$canvas.data("gmapDialog", dialog);
					
					//Create the progress bar - there are not enough locations at the time of testing this to be sure it works, so it may need adjustment. Remove this part of the comment when it is confirmed.
					var progress = $canvas.siblings(".progress").hide();
					$canvas.data("gmapProgressBar", progress);
					
					
					google.maps.event.addListenerOnce(map, "idle", function(){
						$canvas.trigger("gmapready");
						$canvas.data("gmapReady", true);									
						
						P.attachMapControls(map, $canvas.siblings(".controls"));
					});
					
					google.maps.event.addListener(map, "idle", function(){
						//console.log(this.getCenter().toString());
					});
					
					
			});
			
			
			
			
			return this;
		},
		
		initMapControls:function(controls){
			
			//CREATE THE MAP CONTROLS
			controls.each(function(e, el){

				var controls = $(el);					
					
				//Create the zoomer dude.
				var zoom = controls.find(".zoom"),
					zoomSlider = zoom.find(".slider");
				zoomSlider.slider({min:0, max:20, step:1, value:10});				
				
				zoom.find(".in").button({text:false, icons:{primary:"ui-icon-circle-plus"}});
				zoom.find(".out").button({text:false, icons:{primary:"ui-icon-circle-minus"}});
				zoom.find(".buttons").buttonset();
				
				//Create misc controls
				var misc = controls.find(".misc"),
					btnReset = misc.find(".reset");
					
				misc.find("button").button();
				misc.buttonset();
				
				//Create the pan controls.
				var pan = controls.find(".pan");
					
				pan.find(".up").button({text:false, icons:{primary:"ui-icon-circle-arrow-n"}});
				pan.find(".down").button({text:false, icons:{primary:"ui-icon-circle-arrow-s"}});
				pan.find(".left").button({text:false, icons:{primary:"ui-icon-circle-arrow-w"}});
				pan.find(".right").button({text:false, icons:{primary:"ui-icon-circle-arrow-e"}});
				pan.buttonset();
				
				//Create the map type control.
				var mapType = controls.find(".map-type");
					
				mapType.buttonset();
				
				
			
			});
			
		},
		
		attachMapControls:function(map, controls){
			var $canvas = $(map.getDiv()),
				dialog = $canvas.data("gmapDialog");
			
			site.pages.common.setMapReset(map);
			
			//CREATE THE MAP CONTROLS
			controls.each(function(e, el){

				var controls = $(el);					
					
				//Create the zoomer dude.
				var zoom = controls.find(".zoom"),
					zoomSlider = zoom.find(".slider");
					
								
				zoomSlider.bind("slidechange", function(evt, ui){
					map.setZoom(ui.value);	
				});				
				zoom.find(".in").click(function(evt){
					map.setZoom(map.getZoom()+1);
				});
				zoom.find(".out").click(function(evt){
					map.setZoom(map.getZoom()-1);
				});
				zoom.find(".buttons").buttonset();
				
				//Create misc controls
				var misc = controls.find(".misc"),
					btnReset = misc.find(".reset");
				
					
				misc.find("button").button();
				misc.buttonset();				
				
				
				btnReset.click(function(evt){					
					map.setZoom(btnReset.data("gmapResetZoom"));
					map.setCenter(btnReset.data("gmapResetCenter"));
					map.setMapTypeId(btnReset.data("gmapResetMapTypeId"));
				});
				
				//Create the pan controls.
				var pan = controls.find(".pan"),
					panPercent = .35;
				
				pan.find(".up").click(function(evt){
					map.panBy(0, -($canvas.height()*panPercent));
				});
				pan.find(".down").click(function(evt){
					map.panBy(0, ($canvas.height()*panPercent));
				});
				pan.find(".left").click(function(evt){
					map.panBy(-($canvas.width()*panPercent), 0);
				});
				pan.find(".right").click(function(evt){
					map.panBy(($canvas.width()*panPercent), 0);
				});
				pan.buttonset();
				
				//Create the map type control.
				var mapType = controls.find(".map-type"),
					mapTypeRadios = mapType.find("input[name='maptype']");
				mapTypeRadios.each(function(r, radio){
					radio.value = google.maps.MapTypeId[radio.value];
				});
				mapTypeRadios.change(function(){
					var mapTypeId = mapTypeRadios.filter(":checked").val();
					map.setMapTypeId(mapTypeId);
				});
				mapType.buttonset();
				
				
				//Update the necessary controls when the map changes.
				var updateControls = function(evt){
					var mapTypeReg =  map.mapTypes[map.getMapTypeId()];
					zoomSlider.slider("value", map.getZoom());
					zoomSlider.slider("option", "min", mapTypeReg.minZoom);
					zoomSlider.slider("option", "max", mapTypeReg.maxZoom);
					mapTypeRadios.filter("[value='"+map.getMapTypeId()+"']").attr("checked","checked");
					mapType.find("input").button("refresh");
				};
				updateControls();
				google.maps.event.addListener(map, "idle", updateControls);	
				
			});
		},
		
		addMapVcards:function(map, $vcards, chunkOpts){
			var  I = this;
			
			chunkOpts = $.extend({
				chunk:50,
				delay:10,
				complete: function(map, $vcards){}
			}, chunkOpts);
			
			if(!($vcards instanceof $)) $vcards = $(vcards);
			
			var $canvas = $(map.getDiv()),
				dialog = $canvas.data("gmapDialog"),
				progress = $canvas.data("gmapProgressBar"),
				v = 0;
			
			
			var addChunk = function(){
				//CREATE MARKERS AND INFO WINDOWS FOR LISTINGS
				var $chunkVcards = $vcards.slice(v, v+chunkOpts.chunk),
					tmpV = 0;
				//console.log("Processing vcards "+v+"-"+(v+chunkOpts.chunk) + " of "+$vcards.length);
				$chunkVcards.each(function(e, el){
	
					var $vcard = $(el),
						vcard = I.getVcardInfo(el);
					
					if(isNaN(vcard.lat) || isNaN(vcard.lng) || !vcard.lat || !vcard.lng) return;
					
					var icon = new google.maps.MarkerImage(site.paths.root+vcard.markerImg, new google.maps.Size(19,24), new google.maps.Point(0, 0), new google.maps.Point(9, 23)),
						latlng = vcard.latlng,
						marker = null;
					
					//Does a marker at this position already exist?
					for(var m=0; m < map.markerHandler.markers.length; m++){
						var tmpMarker = map.markerHandler.markers[m];
						if(tmpMarker.getPosition().equals(vcard.latlng) || (vcard.centerId && tmpMarker.centerId == vcard.centerId)){						
							marker = tmpMarker;
							//var centerIcon = new google.maps.MarkerImage("/images/map_markers/category_1.png", new google.maps.Size(19,24), new google.maps.Point(0, 0), new google.maps.Point(9, 23));
							//marker.setIcon(centerIcon);
							break;				
						}
					}
					//Is this listing part of a center?
					//Create a new marker if one doesn't already exist at this point
					if(marker === null){
						marker = new google.maps.Marker({
							position: vcard.latlng,
							title: vcard.name,
							icon:icon,
							visible:false
						});	
						marker.$vcards = $([]);
						
						//Attach center ID to marker
						if(vcard.centerId){
							marker.centerId = vcard.centerId;	
						}
					}
					
					//Track the vcards associated to the marker
					marker.$vcards = marker.$vcards.add($vcard);
					
					//Attach the map objects to the vcard element
					$vcard.data("gmapMarker", marker);
					$vcard.data("gmapIcon", icon);
					$vcard.data("gmapLatLng", latlng);					
					
					map.markerHandler.add(marker);
					//map.markerHandler.markers.push(marker); //push them directly onto the array so that we can avoid the markers flashing
					
					tmpV = e;
				});
				v += tmpV+1;
				//console.log("Processed "+v+" vcards of "+$vcards.length);
				if(v < $vcards.length){
					setTimeout(addChunk, chunkOpts.delay); // might need to assign this to a variable at some point so that we can clear it, if overlapping/conflicting calls are made to addMapVcards()
				}else{
					chunkOpts.complete(map, $vcards);
				}
			};
			
			addChunk();
			
				
			
			
			return this;
		},
		
		getVcardInfo:function(el, isRefresh){
			var $vcard = $(el),
				vcard = $vcard.data("vcard");
			if(!isRefresh && vcard){
				return vcard; 	
			}
			
			vcard = {
					el:el,
					name: $vcard.find(".organization-name").text(),
					lat: parseFloat($vcard.find(".latitude").text()),
					lng: parseFloat($vcard.find(".longitude").text()),
					markerImg: $.trim($vcard.find(".marker").text()),
					categories:[],
					categoryGroups:[],
					categoriesMap:{},
					centerId:$.trim($vcard.find(".center").text()),
					primaryCategory:null,
					isInCategory:function(catId){
						return $.inArray(parseInt(catId), this.categories) > -1;
					},
					isInCategoryArray:function(catIds){
						var is = false;
						for(var c=0; c < this.categories.length; c++){
							for(var c2=0; c2 < catIds.length; c2++){
								if(this.categories[c] == parseInt(catIds[c2])){
									is = true;
									break;	
								}
							}
						}
						return is;
					},
					isInCategoryGroup:function(groupId){
						return $.inArray(parseInt(groupId), this.categoryGroups) > -1;
					},
					latlng: null
				};
				
			if(!vcard.centerId.length){
				vcard.centerId = null;	
			}
				
			var cats = $.trim($vcard.find(".categories").text()).split(/\,/);
			if(cats.length){
				for(var c=0; c<cats.length; c++){
					var csplit = cats[c].split(":"),
						cId,
						gId;
					if(csplit.length === 1){
						var cId = parseInt(csplit[0]);
						if($.inArray(cId, vcard.categories) < 0) vcard.categories.push(cId);	
						
					}else if(csplit.length === 2){
						gId = parseInt(csplit[0]);
						cId = parseInt(csplit[1]);
						if($.inArray(gId, vcard.categoryGroups) < 0) vcard.categoryGroups.push(gId);
						if($.inArray(cId, vcard.categories) < 0) vcard.categories.push(cId);
						if(!vcard.categoriesMap[gId]){
							vcard.categoriesMap[gId] = [];	
						}
						if($.inArray(cId, vcard.categoriesMap[gId]) < 0) vcard.categoriesMap[gId].push(cId);
					}
					//set categories
					//set category groups with categories
					//set category groups
				}
				vcard.primaryCategory = vcard.categories[0];
			}			
			
			vcard.latlng = new google.maps.LatLng(vcard.lat, vcard.lng);
			$vcard.data("vcard", vcard);
			return vcard;
		},
		
		filterVcards:function($vcards, catId, catGroupId){
			var I = this,
				results = [];
			$vcards.each(function(el, el){
				var vcard = I.getVcardInfo(el);
				if(catId > 0 && vcard.isInCategory(catId)){
					results.push(el);
				}else if(catGroupId > 0 && vcard.isInCategoryGroup(catGroupId)){
					results.push(el);
				}
			});
			return $(results);
		},
		
		removeMapVcards:function(map, vcards){
			if(!(vcards instanceof $)) vcards = $(vcards);
			vcards.each(function(vc, vcard){
				var $vcard = $(vcard),
					marker = $vcard.data("gmapMarker");							
				map.markerHandler.remove(marker);
			});
			return this;	
		},
		
		setMapReset:function(map){
			var $canvas = $(map.getDiv()),
				controls = $canvas.siblings(".controls"),
				btnReset = controls.find(".reset");
			
			btnReset.data("gmapResetZoom", map.getZoom());
			btnReset.data("gmapResetCenter", map.getCenter());
			btnReset.data("gmapResetMapTypeId", map.getMapTypeId());	
		},
		
		prepAdminActions:function(){
			var $actions = $(".admin-actions");
			
			$actions.each(function(d, div){
				var $div = $(div),
					scope = $div.parent().addClass("admin-action-scope");
				
					
				$div.children(".edit").button({
					text:false,
					icons:{primary:"ui-icon-pencil"}
				});
				
				$div.buttonset();
			});
			
			return this;
		}		
		
		
	});
	
	
	
	
	
	
	site.pages["directory-map"] = new esf.site.Page({
		test:function(){
			return $("body").hasClass("directory-map");
		},
		init:function(){
			this.el = {};
			
			var I = this,
				mapArea = this.el.$mapArea = $("#directory-map"),
				mapCanvas = this.el.$mapCanvas = mapArea.find(".canvas"),
				map = this.map = mapCanvas.data("gmap"),
				mapDialog = this.mapDialog = mapCanvas.data("gmapDialog"),
				progressBar = this.progressBar = mapCanvas.data("gmapProgressBar").show(),
				vcards;			
			
			var mapFilter = this.mapFilter = mapArea.siblings(".map-filter"),//.accordion({collapsible:true, active:false, clearStyle:true}),
				mapFilterContent = this.mapFilterContent = $(mapFilter.attr("data-ajaxContent")),
				filterCategories = mapFilter.find(".categories"),
				cbCategories = this.cbCategories = filterCategories.find(":checkbox"),
				btnFilter = mapFilter.find(".btn-filter").button({icons:{primary:"ui-icon-refresh"}}),
				loadText = "";
			
			
			cbCategories.change(function(evt){				
				
				if(!cbCategories.filter(":checked").length){
					alert("You must select at least one category.");
					this.checked=true;
					//$(this).button("refresh");
				}else{
					//$(this).button({icons:{primary: this.checked ? "ui-icon-check" : "ui-icon-radio-off"}});
					I.refreshFilteredMarkers();
				}
			});
			
			
			map.markerHandler.mapEventListeners.unbind();
			
			
			var req = null,
				tsSubmit, tsLoaded, tsProcessed;
				
			mapFilter.submit(function(evt){
				tsSubmit = new Date();
				progressBar.show();
				
				var loadText = "";
				
				//Uncheck all categories so that we get all listings back
				cbCategories.filter(":checked").each(function(){
					$(this).addClass("checked");
					this.checked = false;
				});
				
				
				var opts = {
					url: mapFilter.attr("action")+mapFilter.serialize(),
					type: mapFilter.attr("method").toUpperCase(),
					dataType:"text",
					cache: true, //cache "false" will append a query string to the URL that will result in a 404
					//ifModified:true,
					//data: mapFilter.serialize(),
					error: function(){
						
					},
					beforeSend:function(jqXHR, settings){
						//console.log(arguments);
						
					},
					success: function(data){
						console.log("success");
						tsLoaded = new Date();
						//var content = $(data);
						
						
						//Remove all of the markers.
						if(vcards!=null){
							site.pages.common.removeMapVcards(map, vcards);
						}

						//Empty the content area and add them to the map.
						mapFilterContent.empty().append(data);
						
						vcards = mapFilterContent.children(".vcard");
						
						//Add the shopping centers first
						site.pages.common.addMapVcards(map, vcards.filter(".category-1"), {complete:function(){
						
							site.pages.common.addMapVcards(map, vcards.not(".category-1"), {complete:function(){
								$.each(map.markerHandler.markers, function(m, marker){
									//Create the marker click action
									I.createMarkerClick(marker, mapDialog);
								});
								
								
								I.refreshFilteredMarkers();
								
								//I.refreshCategoryMarkers(map.markers.g);								
								
								tsProcessed = new Date();
								console.log("Loaded "+ vcards.length +" listings in "+((tsLoaded - tsSubmit)/1000));
								console.log("Processed "+ vcards.length +" listings in "+((tsProcessed - tsLoaded)/1000));
								//progressBar.fadeOut();
							}});	
						
						}});
						
						
					}
				};
				req = $.ajax(opts);
				
				//Recheck previously checked categories
				cbCategories.filter(".checked").each(function(){
					$(this).removeClass("checked");
					this.checked=true;
				});

				return false;
			});
			
			
			
			
			
			google.maps.event.addListener(map, "idle", function(){
				if(this.markerHandler && this.markerHandler.markers.length){
					//I.refreshFilteredMarkers();	// we're not filtering based on "is visible in pane" anymore, so the filtering doesn't have to be done every time the map moves.
				}
			});

		},
		
		load:function(){
			var I = this;
			//Auto-submit the filter form to get the initial locations
			google.maps.event.addListenerOnce(I.map, "idle", function(){
				
			});
			
			I.mapFilter.submit(); //moved this outside of the idle event since we're in the page load event. seems to be safe here
		},
		
		isRefreshing:false,
		refreshChunk:10,
		refreshChunkDelay:10,
		
		refreshFilteredMarkers:function(markers){
			var I = this,
				mapBounds = this.map.getBounds();
			
			if(!markers) markers = I.map.markerHandler.markers;

			var categories = this.getActiveCategories(),
				$vcards = this.mapFilterContent.children(".vcard"),
				v = 0,
				pass = 1;
				
			I.progressBar.show();
			
			var chunkFindMatches = function(){
				I.isRefreshing = true;
				
				var $chunkVcards = $vcards.slice(v, v+I.refreshChunk),
					tmpV = 0;
				
					
				$chunkVcards.each(function(e, el){
					var $vcard = $(el),
						vcard = site.pages.common.getVcardInfo(el),
						marker = $vcard.data("gmapMarker"),
						isInActiveCat = vcard.isInCategoryArray(categories);
					if(marker && isInActiveCat){
					//if(marker && mapBounds.contains(vcard.latlng) && isInActiveCat){
						$vcard.removeClass("hidden");
					}else if(marker){
						$vcard.addClass("hidden");
					}else{
						$vcard.addClass("hidden");
						//console.log("No marker for "+vcard.name);	
					}
					tmpV = e;
				});
				v+=tmpV+1;
				
				
				//console.log("Filtered "+ m + " vcards of " +$vcards.length);
				if(v < $vcards.length){
					setTimeout(chunkFindMatches, I.refreshChunkDelay);
				}else{
					//I.isRefreshing = false;
					//I.progressBar.hide();
					chunkHandleMarkers();
				}
			};
			
			var m = 0;
			
			
			var chunkHandleMarkers=function(){
				
				var chunkMarkers = markers.slice(m, m+I.refreshChunk),
					tmpM = 0;
					
				$.each(chunkMarkers, function(i, marker){
					
					var $visible = marker.$vcards.not(".hidden"),
						icon = $visible.data("gmapIcon");
					if($visible.length){
						if(!marker.getVisible()){
							marker.setVisible(true);	
						}
						
						//Set the title and icon based on center/multi-spot listings
						if($visible.length > 1){
							var $center = marker.$vcards.filter(".category-1").removeClass("hidden"),
								centerVcard;
							if($center.length){
								centerVcard = site.pages.common.getVcardInfo($center);
								icon = $center.data("gmapIcon");
								if(marker.getIcon() != icon){
									marker.setIcon(icon);
								}
								marker.setTitle(centerVcard.name + " - "+$visible.length+" Listings");
							}else{
								marker.setTitle($visible.length + " Listings");
								if(marker.getIcon() != icon){							
									marker.setIcon(icon);	
								}
							}
						}else{
							var vcard = site.pages.common.getVcardInfo($visible);
							marker.setTitle(vcard.name);
							if(marker.getIcon() != icon){							
								marker.setIcon(icon);	
							}	
						}
						
					}else{
						marker.setVisible(false);	
					}
					
					tmpM = i;
				});
				m+=tmpM+1;
				
				if(m < markers.length){
					setTimeout(chunkHandleMarkers, I.refreshChunkDelay);
				}else{
					I.isRefreshing = false;
					I.progressBar.hide();
				}
				
			};
			
			chunkFindMatches();
			
			
			
			
		},
		
		getActiveCategories:function(){
			var I = this,
				categories = [];
			I.cbCategories.filter(":checked").each(function(){
				[].push.apply(categories, this.value.split("|"));
			});
			//console.log("active categories: ",categories); 
			return categories;
		},
		
		createMarkerClick:function(marker, dialog, onClick){
					
			
			if(marker.$vcards.length > 1){
				//If there is a shopping center in the vcards, use it as the title
				var shopCenter = marker.$vcards.filter(".category-1").not(".hidden");
				if(shopCenter.length){
					marker.setTitle($.trim(shopCenter.first().find(".org").text()) + " ("+(marker.$vcards.length)+")");
				}
				//Otherwise, just show how many listings are represented by this marker
				else{
					marker.setTitle((marker.$vcards.length) + " Directory Listings");
				}
			}else{
				marker.setTitle($.trim(marker.$vcards.find(".org").text()));	
			}
			
			google.maps.event.clearListeners(marker, "click");
			google.maps.event.addListener(marker, "click", function() {
					
					//iw.open(map, this);
					var center = this.$vcards.filter(".category-1").not(".hidden"),
						contents = !center.length ? this.$vcards.clone() : center.clone(), //If we have a shopping center, only show it in the info window
						title = this.getTitle(),
						//title = content.find(".org").remove(),
						dialogTitle = dialog.dialog("widget").find(".ui-dialog-titlebar"),
						dialogContent = dialog.dialog("widget").find(".ui-widget-content");				
					
					dialog.empty().prepend(contents);
					
					
					if(this.$vcards.length === 1){
						var vcardOrg = contents.find(".org").remove();
						
						var buttons = {
							"More Info":function(){window.location = vcardOrg.find("a").get(0).href;}
						};
						dialog.dialog("option", "buttons", buttons);
						
					}else{
						dialog.dialog("option", "buttons", null);	
					}
					
					
					if(contents.length > 2){
						dialog.dialog("option", "height", 300);
					}else{
						dialog.dialog("option", "height", "auto");
					}
					
					
					//Put some icons in the vcards
					contents.each(function(){						
						var $vcard = $(this),
							$icon = $vcard.children(".icon"),
							$marker = $vcard.find(".marker");
						
						if(!$icon.length){
							$icon = $("<span class='icon'><img src='"+$.trim($marker.text())+"'/></span>").prependTo($vcard);
						}						
					});
					
					//Set the dialog title and open it
					dialog.dialog("option", "title", title);					
					dialog.dialog("open");
					
					
					//console.log(dialog.dialog("buttons"));
					//btnMore.button("widget").removeClass("ui-state-hover").removeClass("ui-state-focus");
					dialogTitle.addClass("ui-state-hover");
					setTimeout(function(){
						dialogTitle.removeClass("ui-state-hover");
					}, 500);
				});
					

				
		}
		
		
	});
	
	
	
	
	site.pages["directory-listing"] = new esf.site.Page({
		test:function(){
			return $("body").hasClass("directory-listing");
		},
		init:function(){
			
		},
		
		load:function(){
			
			var I = this,
				listingArea = $(".page-main .listing"),
				mapArea = $("#listing-map"),
				mapCanvas = mapArea.find(".canvas"),
				map = mapCanvas.data("gmap"),
				mapDialog = mapCanvas.data("gmapDialog"),
				vcard = listingArea.find(".vcard");
			
			
			site.pages.common.addMapVcards(map, vcard, {complete:function(){
				
			}});	
			map.markerHandler.refresh();
			
			I.createVcardMarkerClick(vcard, mapDialog);
			
			
			var marker = vcard.data("gmapMarker");	
			marker.setVisible(true)
			
			if(!marker){
				mapArea.hide();	
			}else{
				map.setCenter(marker.getPosition());
				site.pages.common.setMapReset(map);
			}
			
		},
		
		createVcardMarkerClick:function(vcard, dialog){
			
			var $vcard = $(vcard),
				marker = $vcard.data("gmapMarker");
			
			google.maps.event.addListener(marker, "click", function() {
					
					//iw.open(map, this);
					var content = $vcard.clone().data("vcard", $vcard.get(0)),
						title = content.find(".org").remove(),
						titlebar = dialog.dialog("widget").find(".ui-dialog-titlebar");
					
					dialog.empty().prepend(content);
					
					var buttons = {
						"Get Directions":function(){window.open($vcard.siblings(".google-link").find("a").get(0).href, "_blank");}
					};	
					
					dialog.dialog("option", "title", title.text());
					dialog.dialog("option", "buttons", buttons);
					dialog.dialog("open");
					
					//console.log(dialog.dialog("buttons"));
					//btnMore.button("widget").removeClass("ui-state-hover").removeClass("ui-state-focus");
					titlebar.addClass("ui-state-hover");
					setTimeout(function(){
						titlebar.removeClass("ui-state-hover");
					}, 500);
				});
				
		}
	});
	
	
	
	site.pages["contact"] = new esf.site.Page({
		test:function(){
			return $("body").hasClass("contact-index");
		},
		init:function(){
			var I = this,
				listingArea = $(".page-main .listing"),
				mapArea = $("#offices-map"),
				mapCanvas = mapArea.find(".canvas"),
				map = mapCanvas.data("gmap"),
				mapDialog = mapCanvas.data("gmapDialog"),
				vcard = $("#sitePage .page-left .vcard");
				
			if(!vcard.length){
				mapArea.hide();
				return;
			}
			
			var idleListener = google.maps.event.addListener(map, "idle", function(evt){
				google.maps.event.removeListener(idleListener);
				site.pages.common.addMapVcards(map, vcard);
				I.createVcardMarkerClick(vcard, mapDialog);
				
				var marker = vcard.data("gmapMarker");	
				
				map.setCenter(marker.getPosition());
				site.pages.common.setMapReset(map);
				
			});
		},
		
		createVcardMarkerClick:function(vcard, dialog){
			
			var $vcard = $(vcard),
				marker = $vcard.data("gmapMarker");
			
			google.maps.event.addListener(marker, "click", function() {
					
					var content = $vcard.clone().data("vcard", $vcard.get(0)),
						title = content.find(".org").remove(),
						titlebar = dialog.dialog("widget").find(".ui-dialog-titlebar");
					
					dialog.empty().prepend(content);
					
					/*var buttons = {
						"Get Directions":function(){window.open($vcard.siblings(".google-link").find("a").get(0).href, "_blank");}
					};					
					dialog.dialog("option", "buttons", buttons);*/
					
					dialog.dialog("option", "title", title.text());
					dialog.dialog("open");
					
					
				});
				
		}
	});
	
	
	
	site.pages["news-galleries"] = new esf.site.Page({
		test:function(){
			var $body = $("body");
			return $body.hasClass("news-galleries") || $body.hasClass("news-gallery");
		},
		
		init:function(){
			
			if(site.paths.segments[2] == "gallery"){
				this.isSingle = true;	
			}
			
			this.createGallery();
		},
		
		isSingle:false,
		
		createGallery:function(){
			
			// SWFObject embed
			var flashvars = {
				xmlFilePath: "/news/_gallery_xml",
				paramXMLPath: "/themes/third_party/slideshowpro/params/default.xml",
				initialURL: escape(document.location),
				useExternalInterface: "true"				
			}
			
			if(this.isSingle){
				flashvars.xmlFilePath += "/" + site.paths.segments[3];
			}else{
				flashvars.startup="Open Gallery";	
			}
			
			var params = { 
				bgcolor: "#121212",
				allowfullscreen: "true"
			}                
			var attributes = {
				id: "ssp"
			}
			swfobject.embedSWF("/themes/third_party/slideshowpro/slideshowpro.swf", "slideshowpro", "696", "500", "10.0.0", false, flashvars, params, attributes);
			
			return this;	
		}
		
	});
	
	
	
	
	
	

	
})();
