(function($){
  
  var ContactSection = function(options, elem) {
    
		var DEFAULT_LOCATION_ID = 7;

    var $this = $(elem),
				$body = $('body');
				$contactContainer = $this.find('.contact-container');
				$contactSections = null,
				$mapContainer = null,
				$mapCanvas = null,
				_pWhere = null,
				_pContact = null,
				_pMap = null,
				_pRibbonNav = null,
				_curContactSectionIndex = -1;
    
    // ----------------------------------------------------------------
    
    function _init() {
      // apply section title plugin to title
			$this.find('.section-title').sectionTitle();
			
			// add padding to the top of section
			$this.find('.regular-content').css('padding-top', '75px');
			
			// create map 
			var mapCanvasMkup = '<div id="map-container">'+
													  '<div id="map-canvas"></div>'+
													'</div>';
													
			$mapContainer = $.browser.msie ? $(innerShiv(mapCanvasMkup, false)) : $(mapCanvasMkup);
			$this.prepend($mapContainer);
			var mapPosTop = Number($('section.contact .regular-content').css('padding-top').split('px')[0]) + Number($('section.contact .section-title').outerHeight());
			$mapContainer.css("top", mapPosTop+"px");
			
			$mapCanvas = $mapContainer.find('#map-canvas');
			_pMap = $mapCanvas.mapPlugin().data('MapPlugin');
			
			$contactSections = $('#where, #contact-form');
			_pRibbonNav = $contactContainer.ribbonNav({ribbonSections:$contactSections}).data("RibbonNav");
						
			_pWhere = $('#where').wherePlugin().data('WherePlugin');
			_pContact = $('#contact-form').contactForm().data('ContactForm');
		
			$contactContainer.bind(MomentumWW.events.RIBBON_NAV_CLICK+'.contactSection', _onContactRibbonNavClick);
			
			$('body').bind(MomentumWW.events.LOCATION_CONTACT_CLICK, _onLocationContactClick);
			
			_gotoContactSection(0);
			_activate();
    }; // _init()
    
    // ----------------------------------------------------------------
		
		function _onContactRibbonNavClick(e, index) {
			debug.log("_onContactRibbonNavClick :: index: "+index);
			_pContact.useContactTypes();
			_gotoContactSection(index);
		};
		
		function _onLocationContactClick(e, hasEmail, officeId) {
			debug.log("_onLocationContactClick :: hasEmail: "+hasEmail+" officeId: "+officeId);
			
			if (hasEmail) {
				_pContact.useOfficeEmail(officeId);
			} else {
				_pContact.useContactTypes();
			}
			
			_gotoContactSection(1);
		}

		function _gotoContactSection(contactSectionIndex) {
			if (_curContactSectionIndex != contactSectionIndex) {
				if (_curContactSectionIndex != -1) {
					// we have a current feature - need to deactivate it first
					var $curContactSection = $contactSections.eq(_curContactSectionIndex);
					$curContactSection.data($curContactSection.data("pluginName")).deactivate();
				}

				// activate new feature
				var $destContactSection = $contactSections.eq(contactSectionIndex);
				$destContactSection.data($destContactSection.data("pluginName")).activate();

				// update nav
				_pRibbonNav.setSelectedBtn(contactSectionIndex);

				_curContactSectionIndex = contactSectionIndex;
			}
		};
		
		function _activate() {
			$body.bind(MomentumWW.events.OFFICE_LOCATION_SELECTED, _onOfficeLocationSelected);
		}
		
		function _onOfficeLocationSelected(e, locationId) {
			_setOfficeLocation(locationId);
		}
		
		function _setOfficeLocation(locationId) {
			_pMap.setLocation(locationId, _pWhere.getCoordsByLocationId(locationId));
			_pWhere.setSelectedOffice(locationId);
		}
		
    _init();
    
    return {
      initializeMap: function() {
				$mapCanvas.data("MapPlugin").initializeMap();
				_setOfficeLocation(DEFAULT_LOCATION_ID);
			},
			
			activate: function() {
				//_activate();
			},
			
			deactivate: function() {
				//_deactivate();
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.contactSection = function(options) {
    
    var pluginName = "ContactSection";
    
    options = $.extend({}, $.fn.contactSection.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
      // No JavaScript plugin instance exists, so add it as data attribute.
      var pluginInstance = new ContactSection(options, this);
      $this.data(pluginName, pluginInstance);
      $this.data('sectionController', pluginInstance);
    });
    
  };
  
  // ==================================================================
  
  $.fn.contactSection.defaults = {
    
  };

	// ==================================================================
 	// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	// ==================================================================

	// @MapPlugin
	var MapPlugin = function(options, elem) {
 
	  var $this = $(elem),
				_mapCanvas = $this[0],
				_map = null,
				_markerLocationInfo = null,
				_curMarker = null,
				CustomMarker = null;
 
	  // ----------------------------------------------------------------
 
	  function _init() {
				// load map script
				//localhost: ABQIAAAAPfJ1T2SGIwFvgEz0LPOUfhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxS4HbaOvUNtrvo1lzl7HwlQlmQ5-Q
				//momentumww: ABQIAAAAPfJ1T2SGIwFvgEz0LPOUfhQIgFKukSobzONlVKmumixoJC2oYhT6MIFPPPDr6DDgprZHyAfhdkzwVQ
				//API v3 (*.momentumww.com/* ; *.localhost): AIzaSyCU6vhXblIaPsPG8Ovyeq0jbkQEG5x_2Sk
				var script = document.createElement("script");
				script.type = "text/javascript";
				script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap";
				document.body.appendChild(script);		
	  }; // _init()

		function _initializeMap() {
			debug.log("_initializeMap :: ");
	
			// define custom marker
			CustomMarker = function($locationInfo, latlng,  map) {
					debug.log("CustomMarker :: constructor");
					this.$locationInfo = $locationInfo;
			    this.latlng_ = latlng;
					this._infoOpen = false;
					
			    // Once the LatLng and text are set, add the overlay to the map.  This will
			    // trigger a call to panes_changed which should in turn call draw.
			    this.setMap(map);
			  }

			CustomMarker.prototype = new google.maps.OverlayView();

		  CustomMarker.prototype.draw = function() {
				var self = this;
				
		    // Check if the div has been created.
		    var div = this.div_;
		    if (!div) {
		      // Create a overlay text DIV
					var divMkup = '<div class="map-marker">'+
													'<div class="map-marker-image"></div>'+
												'</div>';
						
					var $div = $(divMkup)
		      div = this.div_ = $div[0];
					
					$div.append(this.$locationInfo);
					
		     	/*google.maps.event.addDomListener(div, "click", function(event) {
			        //google.maps.event.trigger(this, "click");
							_toggleInfo();
			    });
			
					if (MomentumWW.IS_IPAD) {
						this.$locationInfo.find('a .minus-btn').bind('click', function (event) {
							_toggleInfo();
						});
					}*/

					var $minusBtn = this.$locationInfo.find('.minus-btn');
                    // set the iPad click event to touchstart so it doesn't run twice.
                    var ua = navigator.userAgent,
                    event = (ua.match(/iPad/i)) ? "touchstart" : "click";

					$minusBtn.bind(event, function (e) {
						e.preventDefault();
						debug.log("minusBtn.click :: do _toggleInfo()");
						_toggleInfo();
						return false;
					});

		      // Then add the overlay to the DOM
		      var panes = this.getPanes();
		      panes.overlayImage.appendChild(div);
					
					debug.log("CustomMarker.draw() :: new div created");
					// create div with toggl open by default
					_toggleInfo();
		    }

		    // Position the overlay 
		    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
		    if (point) {
		      div.style.left = point.x + 'px';
		      div.style.top = (point.y + 25) + 'px';
		    }
				
				function _toggleInfo() {
					//debug.log("_toggleInfo :: "+self._infoOpen);
					if (self._infoOpen) {
						self.$locationInfo.css('opacity','0');
						self._infoOpen = false;
					} else {
						self.$locationInfo.css('opacity','1');
						self._infoOpen = true;
					}
				}
				
		  };

		  CustomMarker.prototype.remove = function() {
				//debug.log("CustomMarker :: remove");
		    // Check if the overlay was on the map and needs to be removed.
		    if (this.div_) {
		      this.div_.parentNode.removeChild(this.div_);
		      this.div_ = null;
					
					this.$locationInfo.css('opacity','0');
					this.$locationInfo.detach();
					this.$locationInfo = null;
		    }
		  };

		  CustomMarker.prototype.getPosition = function() {
		   return this.latlng_;
		  };

			// create map
			var latlng = new google.maps.LatLng(32, -32);
			var mapOptions = {
	      zoom: 3,
				backgroundColor: '#333333',
	      center: latlng,
				mapTypeControl: false,
				panControl:false,
				zoomControl:false,
				streetViewControl:false,
				scrollwheel: false,
	      mapTypeId: google.maps.MapTypeId.SATELLITE
	    };

	    _map = new google.maps.Map(_mapCanvas,
	        mapOptions);
	
			_markerLocationInfo = {};
	
			$(window).bind('resize', _onWinResize);
		};
 
	  // ----------------------------------------------------------------
 
		function _setLocation(id, coords) {
			if (_curMarker)
			{
				_curMarker.setMap(null);
			}
			
			debug.log("MapPlugin: _setLocation :: "+id+ " coords: lat: "+coords.lat+" lng: "+coords.lng);
			var $locationInfoContainer = _markerLocationInfo[id]; // first see if we already have a location info made up for this id
			if ($locationInfoContainer == null) {
				// if not then pull the markup from the original office button and treat it for attaching to the map marker
				var $officeBtn = $('ul.office-nav li[data-id="'+id+'"]');
			  var $locationInfo = $officeBtn.data('location-info');
				
				var locationInfoContainerHtml = '<div class="location-info-container"></div>';
				$locationInfoContainer = $.browser.msie ? $(innerShiv(locationInfoContainerHtml, false)) : $(locationInfoContainerHtml);
				$locationInfo.wrap($locationInfoContainer);
				
				var locationInfoInnerHtml = '<div class="location-info-inner"></div>';
				var $locationInfoInner = $.browser.msie ? $(innerShiv(locationInfoInnerHtml, false)) : $(locationInfoInnerHtml);
				$locationInfo.wrapInner($locationInfoInner);
				
				var locationInfoBgHtml = '<div class="location-info-bg"></div>';
				$locationInfoBg = $.browser.msie ? $(innerShiv(locationInfoBgHtml, false)) : $(locationInfoBgHtml);
				$locationInfo.prepend($locationInfoBg);
				
				$locationInfoContainer = $locationInfo.parent();
				var $infoInner = $locationInfo.find('.location-info-inner');
				
				var contactBtnHtml = '<a class="rounded-link dark" data-has-email="foo" data-office-id="bar" href="#/contact/form">CONTACT US</a>';
				var $contactBtn = $.browser.msie ? $(innerShiv(contactBtnHtml, false)) : $(contactBtnHtml);
				
				var directionsBtnHtml = '<a class="directions-btn rounded-link dark" href="#">DIRECTIONS</a>';
				var $directionsBtn = $.browser.msie ? $(innerShiv(directionsBtnHtml, false)) : $(directionsBtnHtml);
				
				var minusBtnHtml = '<a class="minus-btn" href="#"></a>';
				var $minusBtn = $.browser.msie ? $(innerShiv(minusBtnHtml, false)) : $(minusBtnHtml);
				
				$infoInner.append($contactBtn);
				
				// add directions button
				$infoInner.append($directionsBtn);
				var directionsURI = _getDirectionsURI($locationInfoContainer);
				$directionsBtn.attr('href', directionsURI);
				$directionsBtn.attr('target', '_blank');
				
				// rounded link plugin on the buttons
				$contactBtn.roundedLink();
				$directionsBtn.roundedLink();
				
				
				$infoInner.css('width','1000px');
				$('body').append($locationInfoContainer); // temp append to body so width is computed

				var w = 0;
				$infoInner.children().each(function () {
					var $self = $(this);
					$self.css('float','left');
					var newW = $self.outerWidth();
					
					w = (newW > w) ? newW : w;
					$self.css('float','none');
				});
				
				w+= 40;
				var h = ($locationInfoContainer.outerHeight()+28);
							
				$contactBtn.bind('click', function (e) {
					e.preventDefault();
					$('body').trigger(MomentumWW.events.LOCATION_CONTACT_CLICK, [$officeBtn.data('has-email'), $officeBtn.data('office-id')]);
				});
								
				$locationInfo.css({
																	'width': w+'px',
																	'height':h+'px',
																	'position':'absolute',
																	'top':-h+'px',
																	'left':-w+'px'
																});
				$infoInner.css({
													'width':'100%',
													'position':'absolute',
													'top':'8px',
													'left':'20px'	
												});
				
				$minusBtn.css({
					'position':'absolute',
					'bottom':'-19px',
					'right':'21px'
				});
				$infoInner.append($minusBtn);
								
				$locationInfoContainer.css('opacity','0');
				$locationInfoContainer.detach();
				// store the treated locationInfo in an array to reuse it later
				_markerLocationInfo[id] = $locationInfoContainer;
			}
			
			marker = new CustomMarker($locationInfoContainer, new google.maps.LatLng(coords.lat, coords.lng));
			marker.setMap(_map);
			_map.setZoom(13);

			_curMarker = marker;
	
			setTimeout(_doRecenter, 550);
		}
		
		function _getDirectionsURI($locationInfoContainer) {
			var addressStr = '',
					$addressParts = $locationInfoContainer.find('.address');
					
			$addressParts.each(function (n) {
				addressStr += $(this).text();
				if (n + 1 < $addressParts.length) {
					addressStr += ' ';
				}
			});
			addressStr = escape(addressStr)
			//addressStr.split("&").join("%26");
			return directionsURI = 'http://maps.google.com/maps?daddr=' + addressStr;
		}

		function _onWinResize() {
			_doRecenter();
		}

		function _doRecenter() {
			if (_curMarker == null) return;
	
			_map.setCenter(_curMarker.latlng_);
			var qWidth = $this.outerWidth() * 0.25;
			var offsetLatLng = _curMarker.getProjection().fromContainerPixelToLatLng(new google.maps.Point(qWidth, $this.outerHeight() * 0.5));
			_map.setCenter(offsetLatLng);
		}

	  _init();
 
	  return {
	    initializeMap: function() {
				_initializeMap();
			},
	
			setLocation: function(id, coords) {
				_setLocation(id, coords);
			}
	  };
 
	};

	// ==================================================================

	$.fn.mapPlugin = function(options) {
 
	  var pluginName = "MapPlugin";
 
	  options = $.extend({}, $.fn.mapPlugin.defaults, options);
 
	  return this.each(function(){
   
	    var $this = $(this);
   
	    if($this.data(pluginName)) {
	      return;
	    }
   
	    // No JavaScript plugin instance exists, so add it as data attribute.
	    var pluginInstance = new MapPlugin(options, this);
	    $this.data(pluginName, pluginInstance);
   
	  });
 
	};

	// ==================================================================

	$.fn.mapPlugin.defaults = {
 
	};


	// ==================================================================
	// ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	// ==================================================================

	// @WherePlugin
	var WherePlugin = function(options, elem) {
 
	  var $this = $(elem),
				$body = $('body');
				$regionBtns = $this.find('ul.region-nav li'),
	  		$officeNavs = $this.find('ul.office-nav'),
				$officeNavBtns = $this.find('ul.office-nav li'),
				_currentRegionId = null,
				_currentLocationId = null;
 	
	  // ----------------------------------------------------------------
 
	  function _init() {
				$officeNavs.addClass('hidden');
		
				$regionBtns.each(function () {
					var $regionBtn = $(this);
									
					var selectIndicatorMkup = '<div class="select-indicator"></div>';
					var $selectIndicator = $.browser.msie ? $(innerShiv(selectIndicatorMkup, false)) : $(selectIndicatorMkup);
					$regionBtn.append($selectIndicator);
				});
				
				$officeNavBtns.each(function () {
					var $officeBtn = $(this);
					
					var $locationInfo = $officeBtn.find('.location-info');
					$funfact = $locationInfo.find('.fun-fact');
					$funfact.addClass('hidden');
					$funfact.detach();
					
					$locationInfo.detach();
					
					var $locationName = $('<div class="location-name">'+$officeBtn.html()+'</div>');
					$locationInfo.prepend($locationName);
					$officeBtn.append($funfact);
					$officeBtn.data('location-info', $locationInfo);
				});
		
				$this.addClass('hidden');
	  }; // _init()
 
	  // ----------------------------------------------------------------
 
		function _activate() {
	    $regionBtns.bind('click.whereplugin', _onRegionBtnClick);
			$regionBtns.bind('mouseenter.whereplugin', _onBtnOver);
			$regionBtns.bind('mouseleave.whereplugin', _onBtnOut);
			$officeNavBtns.bind('click.whereplugin', _onOfficeBtnClick);
			$officeNavBtns.bind('mouseenter.whereplugin', _onBtnOver);
			$officeNavBtns.bind('mouseleave.whereplugin', _onBtnOut);
			
			$this.css('opacity','0');
			$this.removeClass('hidden');
			$this.stop().animate({opacity:1}, 750, 'easeOutQuart');
		}
	
		function _deactivate() {
	    $regionBtns.unbind('click.whereplugin', _onRegionBtnClick);
			$officeNavBtns.unbind('click.whereplugin', _onOfficeBtnClick);
			
			$this.addClass('hidden');
		}
		
		function _onBtnOver(e) {
			$(this).addClass('hover');
		}
		
		function _onBtnOut(e) {
			$(this).removeClass('hover');
		}

		function _onRegionBtnClick(e) {
			e.preventDefault();
			var regionId = $(this).data('region')
			_setSelectedRegion(regionId);
		}

		function _onOfficeBtnClick(e) {
			e.preventDefault();
			var locationId = $(this).data('id');
			
			$body.trigger(MomentumWW.events.OFFICE_LOCATION_SELECTED, [locationId]);
		}

		function _setSelectedRegion(regionId) {
	
			if (_currentRegionId == regionId) return;
	
			if (_currentRegionId != null) {
				$curRegionBtn = $this.find('ul.region-nav li[data-region="'+_currentRegionId+'"]');
				$curRegionBtn.removeClass('selected');
		
				$this.find('ul.office-nav[data-region="'+_currentRegionId+'"]').addClass('hidden');
				// make sure to unselect any selected office within the region
				_setSelectedOffice(null);
			}
	
			$regionBtn = $this.find('ul.region-nav li[data-region="'+regionId+'"]');
			$regionBtn.addClass('selected');
	
			$this.find('ul.office-nav[data-region="'+regionId+'"]').removeClass('hidden');
			_currentRegionId = regionId;
		}
		
		function _setSelectedOffice(locationId) {
	
			if (_currentLocationId == locationId) return;
			
			if (_currentLocationId != null) {
				var $curOfficeBtn = $this.find('ul.office-nav li[data-id="'+_currentLocationId+'"]');
				$curOfficeBtn.removeClass('selected');
		
				// hide blurb
				// $this.find('ul.office-nav li[data-id="'+_currentLocationId+'"]').addClass('hidden'); 
		
			}
			
			if (locationId) {
					var $officeBtn = $this.find('ul.office-nav li[data-id="'+locationId+'"]');
					
					var regionId = $officeBtn.parent().data('region');
					_setSelectedRegion(regionId)
						
					$officeBtn.addClass('selected');
		
					// show blurb
					//$this.find('ul.office-nav li[data-id="'+locationId+'"]').removeClass('hidden');
				}
				
				_currentLocationId = locationId;
		}

	  _init();
 
	  return {
   		getCoordsByLocationId: function (locationId) {
				var	$officeBtn = $this.find('ul.office-nav li[data-id="'+locationId+'"]');
				//debug.log("getCoordsByLocationId :: "+$officeBtn.html());
				var coords = {
					lat:$officeBtn.data('lat'),
					lng:$officeBtn.data('lng')
				};
				
				return coords;
			},
			
			setSelectedOffice: function(locationId) {
				_setSelectedOffice(locationId);
			},
			
			activate: function () {
				_activate();
			},

			deactivate: function () {
				_deactivate();
			}
	  };
 
	};

	// ==================================================================

	$.fn.wherePlugin = function(options) {
 
	  var pluginName = "WherePlugin";
 
	  options = $.extend({}, $.fn.wherePlugin.defaults, options);
 
	  return this.each(function(){
   
	    var $this = $(this);
   
	    if($this.data(pluginName)) {
	      return;
	    }
   
	    // No JavaScript plugin instance exists, so add it as data attribute.
	    var pluginInstance = new WherePlugin(options, this);
	    $this.data(pluginName, pluginInstance);
   		$this.data("pluginName", pluginName);
	  });
 
	};

	// ==================================================================

	$.fn.wherePlugin.defaults = {
 
	};

  var ContactForm = function(options, elem) {
    
    var $this = $(elem),
				$body = $('body'),
				$container = null,
    		$formContainer = $this.find('#form-container'),
				$form = $this.find('#contact-input'),
				$contentContainer = $('#contact-section .regular-content'),
				$formErrorContainer = null,
				$firstNameInput = null,
				$lastNameInput = null,
				$emailInput = null,
				$commentInput = null,
				$select = null,
				$selectDrop = null,
				$selectMenu = null,
				$selectLabel = null,
				$submitBtn = null,
				$thankYou = $this.find('#thank-you'),
				_isUsingOfficeEmail = false,
				_officeId = null;
    
    // ----------------------------------------------------------------
    
    function _init() {
      
   		$this.addClass('hidden');
			
			var containerMkup = '<div class="container"></div>';
			$container = $.browser.msie ? $(innerShiv(containerMkup, false)) : $(containerMkup);
			$this.append($container);
			
			$container.append($formContainer);
			$container.append($thankYou);
			
			// create custom styled dropdown button
			var selectHtml = '<div id="select" class="clearfix">'+
      							 		 '<a class="rounded-link red" href="#">SELECT A CONTACT OPTION</a>'+
								       '</div>';
			$select = $.browser.msie ? $(innerShiv(selectHtml, false)) : $(selectHtml);
			$form.after($select);
			$selectDrop = $select.find('a');


			// create custom select option menu
			var selectMenuMarkup = '<div class="select-menu"></div>';
			$selectMenu = $.browser.msie ? $(innerShiv(selectMenuMarkup, false)) : $(selectMenuMarkup);
			$selectMenu.addClass('hidden');
			
			/*
			$selectMenu.css({
				'opacity':'0'
			});
			*/
			
			$form.find('select option').each(function () {
				var $opt = $(this),
						value = $opt.attr('value'),
						labelStr = $opt.text();
						
				var optionButtonHtml = '<a href="#" data-value='+value+'>'+labelStr+'</a>';
				var $optionButton = $.browser.msie ? $(innerShiv(optionButtonHtml, false)) : $(optionButtonHtml);
				$selectMenu.append($optionButton);
				
				// add click, rollover handling
				$optionButton.bind('click.selectmenu', _onContactOptionClick);
				$optionButton.bind('mouseenter', function () {
					$(this).addClass('hover');
				});

				$optionButton.bind('mouseleave', function () {
					$(this).removeClass('hover');
				});
				
			});
			
			$select.append($selectMenu);
			
			// create custom submit button
			var submitButtonHtml = '<div id="submit" class="clearfix">'+
      											   '<a class="rounded-link dark" href="#">SUBMIT</a>'+
											       '</div>';
			$submitBtn = $.browser.msie ? $(innerShiv(submitButtonHtml, false)) : $(submitButtonHtml);
			$select.after($submitBtn);
			$submitBtn = $this.find('#submit a'),
			
			// apply plugin to rounded links
			$formContainer.find('.rounded-link').roundedLink();
			
			// create form error container
			var formErrorContainerHtml = '<div id="form-error-container"></div>';
			$formErrorContainer = $.browser.msie ? $(innerShiv(formErrorContainerHtml, false)) : $(formErrorContainerHtml);
			$formContainer.append($formErrorContainer);
			
			// init thank you page styles				
			$thankYou.find(".nav-social-links a").socialLink();
			$thankYou.find('.nav-social-links').css({
				'position':'static',
				'float':'left'
			});
			$thankYou.addClass('hidden');
			
			$thankYou.find(".nav-social-links a").socialLink();
			
			$firstNameInput = $form.find("#firstname");
			$lastNameInput = $form.find("#lastname");
			$emailInput = $form.find("#email");
			$commentInput = $form.find("#comment");
			
			$selectLabel = $select.find('.rounded-link .label');
						
	  }; // _init()

	  // ----------------------------------------------------------------

		function _activate() {
			$this.css('opacity','0');
			$this.removeClass('hidden');
			$this.stop().animate({opacity:1}, 750, 'easeOutQuart');
			
			$formContainer.find('input').each(function () {
				var $input = $(this);
				$input.attr('value', $input.data('default-value'));
				$input.bind('focus', _onInputFocus);
				$input.bind('blur', _onInputBlur);
			});
			
			$formContainer.find('textarea').each(function () {
				var $textarea = $(this);
				$textarea.bind('focus', _onTextareaFocus);
				$textarea.bind('blur', _onTextareaBlur);
			});
						
			$selectDrop.bind('click', _onSelectClick);
			$submitBtn.bind('click', _onSubmitClick);
			
			$contentContainer.css('position','relative');
		};

		function _deactivate() {

			$this.addClass('hidden');
			
			$formContainer.find('input').each(function () {
				var $input = $(this);
				$input.unbind('focus', _onInputFocus);
				$input.unbind('blur', _onInputBlur);
			});
			
			$formContainer.find('textarea').each(function () {
				var $textarea = $(this);
				$textarea.unbind('focus', _onTextareaFocus);
				$textarea.unbind('blur', _onTextareaBlur);
			});
			
			$selectDrop.unbind('click', _onSelectClick);
			$submitBtn.unbind('click', _onSubmitClick);
			
			$contentContainer.css('position','absolute');
		};
		
		function _onInputFocus(e) {
			//debug.log("_onInputFocus :: ");
			var $self = $(this);
			if ($self.attr('value') ==  $self.data('default-value')) 
				$self.attr('value', '');
		};
		
		function _onInputBlur(e) {
			//debug.log("_onInputBlur :: ");
			var $self = $(this);
			if ($self.attr('value') == '') 
				$self.attr('value', $self.data('default-value'));
		};
		
		function _onTextareaFocus(e) {
			//debug.log("_onTextareaFocus :: ");
			var $self = $(this);
			if ($self.attr('value') ==  $self.data('default-value')) 
				$self.attr('value', '');
		};
		
		function _onTextareaBlur(e) {
			//debug.log("_onTextareaBlur :: ");
			var $self = $(this);
			if ($self.attr('value') == '') 
				$self.attr('value', $self.data('default-value'));
		};
		
		function _onSelectClick(e) {
			e.preventDefault();
			
			// open drop down menu
			$selectMenu.removeClass('hidden');
			//$selectMenu.animate({opacity:1}, 0.25, "easeOutQuad");
			
			var eventType = 'mouseup.selectmenu';
			if (MomentumWW.IS_IPAD) {
				eventType = 'touchend.selectMenu'
			}
			
			$body.bind(eventType, _onSelectMenuCancel);
		};
		
		function _onSelectMenuCancel(e) {
			_closeSelectMenu();	
		};
		
		function _closeSelectMenu() {
			var eventType = 'mouseup.selectmenu';
			if (MomentumWW.IS_IPAD) {
				eventType = 'touchend.selectMenu'
			}
			
			$body.unbind(eventType, _onSelectMenuCancel);
			$selectMenu.addClass('hidden');
			//$selectMenu.animate({opacity:0}, 0.25, "easeOutQuad", function () {$selectMenu.addClass('hidden'); });
		};
		
		function _onContactOptionClick(e) {
			e.preventDefault();
			var $optionButton = $(this);
			
			var optionStr = $optionButton.text();
			var optionValue = $optionButton.data('value');
			debug.log("_onContactOptionClick :: optionValue: "+optionValue);
			
			$selectLabel.text(optionStr);
			$selectLabel.data('value', optionValue);
		};
		
		function _onSubmitClick(e) {
			e.preventDefault();
			
			// clearFormErrors
			$formErrorContainer.empty();
			
			// form vars
			var firstName = $firstNameInput.attr('value'),
			 		lastName = $lastNameInput.attr('value'),
					email = $emailInput.attr('value'),
					comment = $commentInput.attr('value');
					
			var	contactType = (_isUsingOfficeEmail) ? 'office_email' : $selectLabel.data('value');
		
			// client side validation
			var isValid = true,
					clientErrors = {};
			if (firstName == $firstNameInput.data('default-value')) {
				clientErrors.firstName = "Please enter a first name.";
				isValid = false;
			}
			
			if (lastName == $lastNameInput.data('default-value')) {
				clientErrors.lastName = "Please enter a last name.";
				isValid = false;
			}
			
			if (email == $emailInput.data('default-value')) {
				clientErrors.email = "Please enter an email adress.";
				isValid = false;
			}
			
			if (comment == $commentInput.data('default-value')) {
				clientErrors.comment = "Please enter a comment.";
				isValid = false;
			}
			
			if (contactType == undefined) {
				clientErrors.contactType = "Please select a contact option.";
				isValid = false;
			}
		
			if (isValid) {
				// submit url and POST data
				var contactSubmitURL = $form.attr('action');
				var formVars = 'firstName='+ firstName +
				 							 '&lastName='+ lastName + 
											 '&email=' + email + 
											 '&comment=' + comment + 
											 '&contactType=' + contactType;
																						
				if (_isUsingOfficeEmail) formVars += '&officeId=' + _officeId;
			
				// ajax submit
				$.ajax({  
				  type: "POST",  
				  url: contactSubmitURL,  
				  data: formVars,  
				  success: function(data) {
						if (data == "success" ) {
				    	debug.log("ajax form submit success :: "+data);
							_displayThankYou();
						} else {
							debug.log("ajax form submit errors:");
							var errors = $.parseJSON(data);
							_displayFormErrors(errors);
						}
				  }  
				});
			} else {
				_displayFormErrors(clientErrors)
			}
		};
		
		function _displayFormErrors(errors) {
			debug.log("*Please fix the following fields:");
			var messageHtml = '<div class="form-error message">'+
											'<p>Please fix the following fields:</p>'+
											'<ul></ul>'+
										'</div>';
			var $message = $.browser.msie ? $(innerShiv(messageHtml, false)) : $(messageHtml);
			var $errorList = $message.find('ul');
			
			for (type in errors) {
				debug.log('error type - '+type+': '+errors[type]);
				var errorHtml = '<div class="form-error '+type+'">*</div>';
				var $error = $.browser.msie ? $(innerShiv(errorHtml, false)) : $(errorHtml);
				$formErrorContainer.append($error);
				
				errorListItemHtml = '<li>'+errors[type]+'</li>';
				var $errorListItem = $.browser.msie ? $(innerShiv(errorListItemHtml, false)) : $(errorListItemHtml);
				$errorList.append($errorListItem);
			}
			
			$formErrorContainer.append($message);
		}
		
		function _displayThankYou() {
			$formContainer.addClass('hidden');
			$thankYou.removeClass('hidden');
		}

    _init();
    
    return {
      activate: function () {
				_activate();
			},

			deactivate: function () {
				_deactivate();
			},
			
			useOfficeEmail: function (officeId) {
				_isUsingOfficeEmail = true;
				_officeId = officeId;
				
				if (!$select.hasClass('hidden')) {
					$select.addClass('hidden');
				}
			},
			
			useContactTypes: function() {
				_isUsingOfficeEmail = false;
				_officeId = null;
				
				if ($select.hasClass('hidden')) {
					$select.removeClass('hidden');
				}
			}
    };
    
  };
  
  // ==================================================================
  
  $.fn.contactForm = function(options) {
    
    var pluginName = "ContactForm";
    
    options = $.extend({}, $.fn.contactForm.defaults, options);
    
    return this.each(function(){
      
      var $this = $(this);
      
      if($this.data(pluginName)) {
        return;
      }
      
      // No JavaScript plugin instance exists, so add it as data attribute.
      var pluginInstance = new ContactForm(options, this);
      $this.data(pluginName, pluginInstance);
      $this.data("pluginName", pluginName);
    });
    
  };
  
  // ==================================================================
  
  $.fn.contactForm.defaults = {
    
  };
  
})(jQuery);


function initializeMap() {
	jQuery('section.container.contact').data('ContactSection').initializeMap();
}
