/**
 * @author michael.paige
 */
var Void = function() {};  if(!console){var console={log:Void, info:Void, error:Void, warn:Void, count:Void, group:Void, groupEnd:Void};}

// global vars for AddThis functionality
var addthis_options = 'email, technorati, favorites, reddit, print, bebo, digg, posterous, delicious, linkedin, twitter, netvibes, bitly, live, facebook, more';
var addthis_config = { username: 'oglivycom', ui_offset_top: -17, ui_offset_left: -125, ui_header_color: '#fff', ui_header_background: '#c5351c' };

var OHW = window.OHW || {};

(function($) {
	$(function() {
		OHW.HeroSpots.Init();
		OHW.OfficeProfileGallery.Init();
		OHW.Articles.Init();
		OHW.ArticlePagination.Init();
		OHW.Share.Init();
		OHW.GoogleMaps.Init();
		OHW.ContactUs.Init();

		// external links will open in new window on click
		$('a').live('click', function(e) {
			if ( $(this).is( '[href^="http://"]' ) && (this.hostname && this.hostname !== location.hostname) ) {
				window.open( this.href );
				return false;
			}
		});
	});

	OHW.Articles = (function() {
		var scrollAPI, locHref, locHash, locHost, articleWrapper, articleIntro, articleScroller, articles, articleLinks;
		
		var clickEvent = false;

		function pageload(hash) {
			// hash should not contain the first # character.
			if(hash) {
				// restore ajax loaded state
				//if($.browser.msie) {
				//	hash = encodeURIComponent(hash);
				//}
				replaceContent(hash);
			} else {
				//refresh the original display
				refreshContent();
			}
		}
		
		function replaceContent(hash) {
			var articleLink = articleLinks.filter('[href$=' + hash + ']:first');
			var GuID = articleLink.attr('GuID');
			//;;;console.info(GuID);

			if ( ! clickEvent ) {
				var parent = articleLink.closest('li');
				var itemIndex = articleLinks.index(articleLink);

				articles.removeClass('active');
				parent.addClass('active');

				scrollAPI.seekTo(itemIndex);
			}

			//make the call
			$.ajax({
				type: 'POST',
				url: '/network/webservices/article.asmx/GetArticle',
				data: $.JSON.encode({ id: GuID }), // JSON.stringify() only works in supporting browsers - will fail in IE 6/7
				dataType: 'json',
				contentType: 'application/json',
				beforeSend: function(xhr) {
					// xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
					// xhr.setRequestHeader('Cache-Control', 'no-cache');
				},
				success: function(data, textStatus) {
					if ( ! articleWrapper.hasClass('articleView') ) {
						articleWrapper.addClass('articleView');
					}
	
					if ( articleIntro.is(':visible') ) {
						articleIntro.hide();
					}
	
					articleWrapper.find('.articleGrid').remove();
	
					//set the data in page
					var html = ( data.d.ItemType !== 'Text' ) ? OHW.ArticleTemplates.videoArticle(data) : OHW.ArticleTemplates.textArticle(data);
					articleWrapper.append(html);
	
					//initialize any objects
				},
				error: function(xhr, textStatus) {
					//;;;console.warn(textStatus);
					//;;;console.warn(xhr.responseText);
					var jsonObj = $.JSON.decode(xhr.responseText);  // JSON.parse() only works in supporting browsers - will fail in IE 6/7
				}
			});
		}
		
		function refreshContent() {
			articleWrapper.find('.articleGrid').remove();

			if ( articleWrapper.hasClass('articleView') ) {
				articleWrapper.removeClass('articleView');
			}

			if ( ! articleIntro.is(':visible') ) {
				articleIntro.show();
			}

			//find any active article in the scroller
			articleScroller.find('li').removeClass('active');
		}
		
		function articleHandler(e) {
			e.preventDefault();
			
			var articleItem = $(this),
				articleLink = articleItem.find('.ctaLink').get(0);

			clickEvent = true;
			
			if ( ! articleItem.hasClass('active') ) {
				articles.removeClass('active');
				articleItem.addClass('active');
		
				var hash = articleLink.href;
				hash = hash.replace(/^.*#/, '');
				hash = trimLinkPath(hash);
				// moves to a new page.
				// pageload is called at once. 
				// hash doesn't contain "#", "?"
				$.historyLoad(hash);
			}
		}
		
		function trimLinkPath(hash) {
			var path = locHref.replace('.aspx' + locHash, '');
			
			return hash.replace(path, '');
		}

		return {
			Init: function() {
				locHref = location.href;
				locHash = location.hash;
				locHost = location.host;
				articleWrapper = $('#articleWrapper');
				articleIntro = $('.articleIntro');
				articleScroller = $('.scrollable');
				articles = articleScroller.find('li');
				articleLinks = articleScroller.find('.ctaLink ');
				
				if ( articleScroller.length > 0 ) {
					// initialize scroller
					scrollAPI = articleScroller.scrollable({
							api: true,
							size: 4,
							clickable: false,
							hoverClass: 'hover'
						});
					
					articleScroller.find('li').bind('click', articleHandler);

					$.historyInit(pageload);
				}
			} // Articles.Init
		}; // returning
	})(); // Articles

	OHW.ArticleTemplates = {
		textArticle: function(data) {
			var data = data.d;
			var imageURL = data.ImageUrl;
			var pdfURL = data.PdfUrl;
			var pages = data.Pages;
			var pagesLength = pages.length;
			var relatedLinks = data.RelatedLinks;
			var relLength = relatedLinks.length;
			
			var html = '<div class="articleGrid">'
					+ '<div class="articleContent">'
						+ '<div class="textArticle">'
							+ '<h3>' + data.Title + '</h3>'
				
							+ '<div class="byline">' + data.ByLine + '</div>'
							
							+ '<div id="bodyContent">';

				// content loop
				for (var i = 0; i < pagesLength; i++) {
					var currentClass = (i === 0) ? ' viewing' : '';
					var articleImage = (i === 0 && imageURL !== '') ? '<img class="articleImage" src="' + imageURL + '" />' : '';

					html += '<div class="contentBlock' + currentClass + '">' + articleImage + pages[i].Content + '</div>';
				}

				html += '</div>'
							+ '<div id="articleNavigation">'
								+ '<div id="pagination">'
									+ '<ul>';
									
									
				if ( pagesLength > 1 ) {
					html += '<li>'
							+ '<a class="prev" href="javascript:void(0);"><span class="angleQuote">&laquo;</span></a>'
						+ '</li>';
					
					// pagination loop
					for ( var i = 0; i < pagesLength; i++ ) {
						var currentClass = (i === 0) ? ' current' : '';
						html += '<li>' + '<a class="disc' + currentClass + '" href="javascript:void(0);">' + i + '</a>' + '</li>';
					}
					
					html += '<li>'
							+ '<a class="next" href="javascript:void(0);"><span class="angleQuote">&raquo;</span></a> <strong>Read More</strong>'
						+ '</li>';
				}

				// if PDF exists
				if ( pdfURL !== '' ) {
					html += '<li class="articleDownload">'
						+ '<a target="_blank" href="' + pdfURL + '"><span class="angleQuote">&raquo;</span> Download PDF</a>'
					+ '</li>';
				}

				html += '</ul>'
								+ '</div>'
							+ '</div>'
						+ '</div>'
					+ '</div>'
					
					+ '<div class="relatedContent">'
						+ '<h4>Related Content</h4>'
						+ '<ul>';

				//related content loop
				for (var i = 0; i < relLength; i++ ) {
					html += '<li>'
							+ '<a href="' + relatedLinks[i].Url + '">' + relatedLinks[i].Text + '</a>'
						+ '</li>';
				}

				html += '</ul>'
					+ '</div>'
				+ '</div>';
			
			return html;
		},
		
		videoArticle: function(data) {
			var data = data.d;
			var relatedLinks = data.RelatedLinks;
			var relLength = relatedLinks.length;
			var content = data.PageSummary;
			
			var html = '<div class="articleGrid">'
					+ '<div class="articleContent">'
						+ '<div class="videoContainer"><div id="ContainerDivId"></div></div>'
						
							+ '<script type="text/javascript">'
								+ 'var swfParams ={"allowFullScreen":"true", "allowScriptAccess":"always", "noCache":"true", "menu":"false", "wmode":"Window"};'
								+ 'var swfVars ={"autoPlay":"true", "url":"' + data.VideoUrl + '"};'
								+ 'var swfAttrs ={"id":"ContainerDivId_SWFObject"};'
								+ 'swfobject.embedSWF("/network/Assets/swf/videoPlayer.swf","ContainerDivId","442","275","10.0.0","",swfVars,swfParams,swfAttrs);'
							+ '</script>'
						
						+ '<div class="articleSummary">'
							+ '<h3>' + data.PageTitle + '</h3>'
							+ content
						+ '</div>'
					+ '</div>'
					
					+ '<div class="relatedContent">'
						+ '<h4>Related Content</h4>'
						+ '<ul>';

				//related content loop
				for (var i = 0; i < relLength; i++) {
					html += '<li>'
							+ '<a href="' + relatedLinks[i].Url + '">' + relatedLinks[i].Text + '</a>'
						+ '</li>';
				}

				html += '</ul>'
					+ '</div>'
				+ '</div>';
			
			return html;
		}
	};

	OHW.ArticlePagination = (function() {
		var articleWrapper, 
			paging = false;
		
		function pageHandler(e) {
			e.preventDefault();

			var _this = e.target,
				paginationContainer = $('#pagination'),
				pageLinks = paginationContainer.find('.disc'),
				current = pageLinks.filter('.current'),
				newIndex = pageLinks.index( _this );
			
			if ( ! $(_this).hasClass('current') ) {
				current.removeClass('current');
				$(_this).addClass('current');
				paging = true;
				showPage( newIndex );
			}
		}
		
		function nextPrevHandler(e) {
			e.preventDefault();

			var _this = e.target,
				paginationContainer = $('#pagination'),
				pageLinks = paginationContainer.find('.disc'),
				pagerLength = pageLinks.length,
				current = pageLinks.filter('.current'),
				currentIndex = pageLinks.index( current ),
				newIndex, newCurrent;
				
			if ( ! $(_this).is('a') ) {
				_this = $(_this).closest('a').get();
			}
			
			if ( !paging ) {
				if ($(_this).hasClass('prev')) {
					if (currentIndex !== 0) {
						newIndex = currentIndex - 1;
					}
				}
				
				if ($(_this).hasClass('next')) {
					if (currentIndex !== (pagerLength - 1)) {
						newIndex = currentIndex + 1;
					}
				}
				
				if (newIndex !== undefined) {
					newCurrent = pageLinks.eq(newIndex);
					
					current.removeClass('current');
					newCurrent.addClass('current');
					paging = true;
					showPage(newIndex);
				}
			}
		}
		
		function showPage(index) {
			var contentContainer = $('#bodyContent'),
				contentBlocks = contentContainer.find('.contentBlock'),
				currentPage = contentBlocks.filter('.viewing'),
				newPage = contentBlocks.eq(index);
			
			currentPage.stop(false, true).fadeOut('fast', function() {
				newPage.fadeIn('fast').addClass('viewing');
				paging = false;
			}).removeClass('viewing');
		}
				
		return {
			Init: function() {
				if ( $('#articleWrapper').length > 0 ) {
					// set default variables
					articleWrapper = $('#articleWrapper');
		
					// set event handlers
					articleWrapper.bind('click', 
						$.delegate({
							'#pagination .disc': pageHandler,
							
							'#pagination .prev, #pagination .prev span, #pagination .next, #pagination .next span': nextPrevHandler
						}) // end $.delegate
					); // article wrapper
				}
			} // ArticlePagination.Init
		}; // returning
	})(); // ArticlePagination


	OHW.OfficeProfileGallery = (function() {
		var imagePreviews, previewLinks, featuredImageContainer, featuredImage;
		
		function previewHandler(e) {
			e.preventDefault();
			
			var _this = $(this),
				viewing = previewLinks.filter('.viewing');
			
			if ( !_this.hasClass('viewing') ) {
				var previewImg = _this.find('img'),
					previewSrc = previewImg.attr('src'),
					newSrc = _this.attr('href'); // previewSrc.replace('preview-92x59', 'featured-468x260');
				
				viewing.removeClass('viewing').find('img').attr('style', null);
				_this.addClass('viewing');
				
				featuredImage.attr('src', newSrc);
			}
		}

		return {
			Init: function() {
				imagePreviews = $('#imagePreviews');
				previewLinks = imagePreviews.find('a');
				featuredImageContainer = $('#featuredImage');
				featuredImage = featuredImageContainer.find('img:first');
				
				previewLinks
					.bind( 'click', previewHandler )
					.hover(
						function() { //mouseover
							if ( !$(this).hasClass('viewing') ) {
								var previewImg = $(this).find('img');
								
								previewImg.stop(true, true).animate({
									opacity: 1
								});
							}
						},
						function() { //mouseout
							if ( !$(this).hasClass('viewing') ) {
								var previewImg = $(this).find('img');
								
								previewImg.stop(true, true).animate({
									opacity: 0.3
								});
							}
						}
					);
			} // OfficeProfileGallery.Init
		}; // returning
	})(); // OfficeProfileGallery


	OHW.HeroSpots = (function() {
		var heroSpots = null,
			heroSpotNav = null,
			heroSpotNavItems = null,
			currentIndex = 0,
			speed = 4500, // rate of rotation
			resumeDelay = 400, // on mouseout resume rotation after delay
			timer = null;

		function createHeroSpotNav() {
			var heroSpotsLength = heroSpots.length;
			
			heroSpots.eq( currentIndex ).show();
			
			for (var i = heroSpotsLength; i--;) {
				heroSpotNav.append('<li><a href="javascript:void(0);">link</a></li>');
			}
			
			heroSpotNavItems = heroSpotNav.find('li');
			heroSpotNavItems.eq( currentIndex ).addClass('current');
			
			start();
		}
		
		function navHandler(e) {
			var _this = e.target,
				index = heroSpotNav.find('a').index( $(_this) );
			
			stop();
			currentIndex = index;
			setHeroSpot();
			//start();
		}
		
		function rotate() { // sequential
			clearTimeout( timer );
			timer = null;

			if ( currentIndex < heroSpots.length - 1 ) {
				currentIndex++;	
			} else {
				currentIndex = 0;	
			}
		
			setHeroSpot();
			timer = setTimeout( function() {
				rotate();
			}, speed);   
		}

		function start() {
			timer = setTimeout( function() {
				rotate();
			}, speed); 
		}

		function stop(e) {
			clearTimeout( timer );
			timer = null;
		}
		
		function resume(e) {
			timer = setTimeout( function() {
				rotate();
			}, resumeDelay );
		}
		
		function setHeroSpot() {
			var _self = this,
				selectedNavItem = heroSpotNavItems.eq( currentIndex ),
				currentHeroSpot = heroSpots.filter(':visible');
			
			if ( !selectedNavItem.hasClass('current') ) {
				heroSpotNavItems.removeClass('current');
				selectedNavItem.addClass('current');
				
				currentHeroSpot.fadeOut('slow');
				heroSpots.eq( currentIndex ).fadeIn('slow');
			}
		}

		return {
		    SetSpeed: function( newSpeed ) {
		        speed = newSpeed;
		    },
			Init: function() {
				if ( $('#heroSpotWrapper').length > 0 ) {
					
					// set default variables
					heroSpots = $('#heroSpots').find('li');
					heroSpotNav = $('#heroSpotNav');
		
					// set event handlers
					$('#content').bind('click', 
						$.delegate({
							'#heroSpotNav a': function(e) {
								e.preventDefault();
								
								navHandler(e);
							}
						}) // end $.delegate
					).bind('mouseover', 
						$.delegate({
							'#heroSpots li': function(e) {
								e.preventDefault();
								
								stop();
							}
						}) // end $.delegate
					).bind('mouseout', 
						$.delegate({
							'#heroSpots li': function(e) {
								e.preventDefault();
								
								resume();
							}
						}) // end $.delegate
					); // content section
		
					createHeroSpotNav();
				}
			} // HeroSpots.Init
		}; // returning
	})(); // HeroSpots

 
	OHW.Share = (function() {
		return {
			Open: function() {
				var url = location.href;
				var title = document.title;
				addthis_open(this, '', url, title);
			},
			Close: function() {
				addthis_close();
			},
			Init: function() {
				$('#shareButton a').hover( 
					OHW.Share.Open, 
					OHW.Share.Close
				);
			}
		}; // returning
	})(); // Share
 
	
	OHW.ContactUs = (function() {
		var contactForm, contactFormFieldset, contactFormFields, contactFormSubmit, contactFormErrors;

		return {
			Init: function() {
				contactForm = $('#contactForm');
				contactFormFieldset = contactForm.find('fieldset:first');
				contactFormFields = contactFormFieldset.find(':input');
				contactFormSubmit = $('#contactFormSubmit');
				contactFormErrors = $('#contactFormErrors');
				
				contactFormFieldset.find('.userInfo').find(':input').watermarkText();
				
				contactFormSubmit.bind('click', function(e) {
					e.preventDefault();
					
					var errorsMsgs = [];
					var requiredFieldError = false;
					var contactFormData = {};
					var interests = [];
					var contactFormInputs = contactFormFieldset.find(':text, :checked, select, textarea');
					var interestsChecked = contactFormFieldset.find(':checked');

					contactFormInputs.closest('.formControl').removeClass('error');

					$.each(contactFormInputs, function(i) {
						var field = $(this),
							fieldTitle = field.attr('title'),
							fieldName = field.attr('name'),
							fieldValue = field.val();

						if ( fieldValue === '' || fieldValue === fieldTitle ) {
							var reqTitle = fieldTitle.replace('*', '');

							if ( requiredFieldError === false ) {
								errorsMsgs.push( 'Please complete all required fields.' );
								requiredFieldError = true;
							}
							field.closest('.formControl').addClass('error');
						} else {
							if ( field.is(':checkbox') ) {
								interests.push(fieldValue);
								contactFormData[fieldName] = interests;
							} else {
								contactFormData[fieldName] = fieldValue;
							}
						}
					});
					
					if ( ! interestsChecked.length > 0 ) {
						errorsMsgs.push( 'Please check at least one Interest.' );
					}
					
					// Cancel submit, display errors
					if ( errorsMsgs.length > 0 ) {
						//;;;console.warn('Please correct the following errors');
						
						var errorsLen = errorsMsgs.length;
						
						if ( contactFormErrors.is(':visible') ) {
							contactFormErrors.hide().empty();
						}
			
						contactFormErrors.append('<h4>Please correct the following errors</h4>');
						
						var errors = $('<ul></ul>');
						
						for ( var i = 0; i < errorsLen; i++ ) {
							var error = $('<li>' + errorsMsgs[i] + '</li>');
		
							errors.append(error);
						}
		
						contactFormErrors.append( errors ).show();
						
						return false;
					}

					$.ajax({
						type: 'get',
						url: 'https://10.29.46.70/Leads.svc/',
						data: JSON.stringify( contactFormData ), // JSON.stringify() only works in supporting browsers - will fail in IE 6/7
						dataType: 'jsonp',
						contentType: 'application/json',
						beforeSend: function(xhr) {
							// xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
							// xhr.setRequestHeader('Cache-Control', 'no-cache');
						},
						success: function(data, textStatus) {
							//console.log(data);
						},
						error: function(xhr, textStatus) {
							//;;;console.warn(textStatus);
							//;;;console.warn(xhr.responseText);
							var jsonObj = $.JSON.decode(xhr.responseText);  // JSON.parse() only works in supporting browsers - will fail in IE 6/7
						}
					});
				});
				
				contactFormFields.bind('focus', function() {
					var parent = $(this).closest('.formControl');

					if ( parent.hasClass('error') ) {
						parent.removeClass('error');
					}
				}).bind('blur', function() {
					// TODO: ?
				});
			}
		}; // returning
	})(); // ContactUs

	OHW.GoogleMaps = (function(){
		var _map = null,
			_geocoder = null,
			_currentQueueItem = null,
			_addressQueue = [],
			redPin = null,
			markerOptions = null,
			_sixTwentyFailed = false;
			
		function GeocodeResponse(response) {
			if (response && response.Status.code != 200) {
			    if( response.Status.code == 620 && _currentQueueItem.__LAST_ATTEMPT !== true ) {
			        // console.log("GeocodeResponse[FAILED-620]: ", _currentQueueItem.Offices[0].Address.Lines, _currentQueueItem.__LAST_ATTEMPT );
			        _currentQueueItem.__LAST_ATTEMPT = true;
			        _sixTwentyFailed = true;
			        OHW.GoogleMaps.QueuePoint(_currentQueueItem);
			    } else {
				    // console.log("GeocodeResponse[FAILED]: ", _currentQueueItem.Offices[0].Address.Lines, _currentQueueItem.__LAST_ATTEMPT );
				    if( ! _currentQueueItem.__LAST_ATTEMPT ) {
				        _currentQueueItem.__LAST_ATTEMPT = true;
				        _currentQueueItem.Offices[0].Address.Lines.reverse();
				        _currentQueueItem.Offices[0].Address.Lines.pop();
				        _currentQueueItem.Offices[0].Address.Lines.reverse();
				        OHW.GoogleMaps.QueuePoint(_currentQueueItem);
			        }	
			    }			    
			} else {
				var place = response.Placemark[0];
				_currentQueueItem.Point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				// console.log("GeocodeResponse[FOUND]: ", _currentQueueItem.Offices[0].Address.Lines, _currentQueueItem.__LAST_ATTEMPT );
				OHW.GoogleMaps.PlotPoint(_currentQueueItem);
			}
			
			_currentQueueItem = null;
			
			ProcessQueue();
		}
		
		function ProcessQueue() {
		    // console.log("There are ", _addressQueue.length, " items left in queue"); 
			// if we're not processing something already and there's stuff in the queue then go
			if( _currentQueueItem === null && _addressQueue.length > 0 && ! _sixTwentyFailed ) {
				_currentQueueItem = _addressQueue.pop();
				GeocodeAddress( _currentQueueItem.Offices[0].Address.Lines.join(" ") );
			}
			
			if( _sixTwentyFailed && _currentQueueItem === null ) {
			    setTimeout( function() { 
			        _sixTwentyFailed = false;
			        ProcessQueue();
			    }, 500 );
			}
		}
		
		function GeocodeAddress(address){
			_geocoder.getLocations(address, GeocodeResponse);
		}
		
		return {
			Init: function() {
				var mapsDiv = $("#googleMaps");
				if( mapsDiv.length > 0 ) {
					_map = new GMap2(mapsDiv.get(0));
					_geocoder = new GClientGeocoder();
		
					// don't know about the next line, except the 2, which is zoom
					_map.setCenter(new GLatLng(40.7875494, -73.9639942), 2);
					_map.setUIToDefault();
					
					$(offices).each(function(index, office){
						OHW.GoogleMaps.QueuePoint(office);
					});
				}
			},
			OfficeHtml: function(office) {
				var featuredOffice = null;
				var offices = office.Offices;
				var html = '';
				
				if ( offices.length > 1 ) {
					html += '<div style="margin-top:10px;overflow:hidden;">'
								+ '<div style="float:left;width:105px;font-size:9px;line-height:11px;color:#000;margin-right:10px;">' 
									+ offices[0].Address.Lines.join('<br />')
									+ '<div style="font-size:10px;padding-top:15px;">';
										
					$.each(offices, function() {
						if ( featuredOffice == null && this.IsFeatured ) {		
							featuredOffice = this;
						}
					});
					
					if( featuredOffice != null ) {
	                    html += '<span style="font-size:13px;color:#c6351c;">&raquo;</span> <a href="' + featuredOffice.FeaturedUrl + '">See Office Profile</a><br />';
	                }
	                
					html += '<span style="font-size:13px;color:#c6351c;">&raquo;</span> <a href="http://maps.google.com/maps?saddr=&daddr=' + office.Point.toUrlValue() + '" target ="_blank">Get Directions</a>'
								+ '</div>'
							+ '</div>'
							+ '<div style="float:left;width:115px;margin-right:10px;">';
	
					$.each(offices, function() {
						html += '<div style="font-size:9px;line-height:11px;color:#000;margin-bottom: 5px;">'
								+ '<div style="color:#c6351c;margin-bottom:2px;">' + this.Name + '</div>'
								+ this.Telephone + '<br />'
								+ ( ( this.Contact != null ) ? 'contact: <a href="mailto:' + this.Contact.EmailAddress + '">' + this.Contact.Name + '</a>' : '' )
							+ '</div>'
					});
					
					if( featuredOffice != null ) {
					    html += '</div>'
							    + (featuredOffice.OfficeMapImageUrl !== null ? '<div style="float:left;width:105px;"><img src="' + featuredOffice.OfficeMapImageUrl + '" width="105" /></div>' : '')
						    + '</div>';
					}
				} else {
					html += '<div style="font-size:10px;font-weight:bold;line-height:24px;color:#c6351c;margin-top:-8px;">' + (offices[0].WebAddress !== '' ? '<a style="color:#c6351c;" href="' + offices[0].WebAddress + '">' + offices[0].Name + '</a>' : offices[0].Name) + '</div>'
						+ '<div style="overflow:hidden;">'
							+ '<div style="float:left;width:105px;font-size:9px;line-height:11px;color:#000;margin-right:10px;">' 
								+ offices[0].Address.Lines.join('<br />') + '<br />' + offices[0].Telephone + '<br />'
								+ '<div style="font-size:6px;color:#c6351c;">CONTACT</div>'
									+ ( ( offices[0].Contact != null ) ? '<a href="mailto:' + offices[0].Contact.EmailAddress + '">' + offices[0].Contact.Name + '</a><br />' : '' )
									+ '<div style="padding-top:3px;">'
										+ (offices[0].IsFeatured ? '<span style="font-size:13px;color:#c6351c;">&raquo;</span> <a href="' + offices[0].FeaturedUrl + '">See Office Profile</a><br />' : '')
										// + (office.WebAddress !== '' ? '<span style="font-size:13px;color:#c6351c;">&raquo;</span> <a href="' + office.WebAddress + '">Visit Website</a><br />' : '')
										+ '<span style="font-size:13px;color:#c6351c;">&raquo;</span> <a href="http://maps.google.com/maps?saddr=&daddr=' + office.Point.toUrlValue() + '" target ="_blank">Get Directions</a>'
									+ '</div>'
								+ '</div>'
							+ ("SpotlightImageUrl" in offices[0] ? '<div style="float:left;width:105px;"><img src="' + offices[0].SpotlightImageUrl + '" width="105" /></div>' : '')
						+ '</div>';
				}

				return html;
			},
			QueuePoint: function(office) {
				_addressQueue.push( office );
				ProcessQueue();
			},
			PlotPoint: function(item) {
				//console.log(item);
				//var marker = new GMarker(item.Point, markerOptions);
				var marker = new GMarker(item.Point);
				
				GEvent.addListener(marker, "click", function() {
					_map.openInfoWindowHtml(item.Point, OHW.GoogleMaps.OfficeHtml(item) );
				});
				
				_map.addOverlay( marker );
			},
			ClearMap: function() { _map.clearOverlays(); }
		};
	})();


	/*
	 * Watermark Text Plugin
	 */
	$.fn.watermarkText = function() {
		return this.each(function() {
			var defaultText = $(this).attr('title');

			$(this).focus(function() {
				if ($(this).val() === defaultText) {
					$(this).val('');
				}
			}).blur(function() {
				if ($(this).val() === '') {
					$(this).val(defaultText);
				}
			});
		});
	};

	$.postJSONP = function(url, data, callback) {
		$.ajax({
			url: url,
			success: callback,
			data: JSON.stringify(data),
			type: 'post',
			dataType: 'jsonp',
			processData: 'false'
		});
	};
	
	$.postJSON = function(url, data, callback) {
		$.ajax({
			url: url,
			success: callback,
			data: JSON.stringify( data ),
			type: 'post',
			dataType: 'json',
			contentType: 'application/json'
		});
	};
}(jQuery));


