/* EpiCity Custom Scripts 
*/

// homepage gallery setup
var currImage = 0;
var left = 10;
var oldLinks = [];
var oldTitles = ['Deals That Fit','Get It Done','Here To Serve',''];
var newLinks = [];
var newTitles = ['Investors','Clients','Customers','Portfolio'];
var fGalTimer = 0;

// company page scrollers setups
var scrollTeamInterval = 0;
var scrollTeamTime = 1;
var scrollHistoryInterval = 0;
var scrollHistoryTime = 10;

//property page features setups
var propFeaturesTime = 4000;
var currPropFeature = 0;
var thePropFeaturesTimer = 0;
var numPropFeatures = 0;
		
var latlng = new google.maps.LatLng(33.784854, -84.385693);
var portfolioMap = 0; // init null
var portfolioMarkers = new Array(); // init array for marker images
var markersArray = new Array(); // init array for map markers and marker events
var infoWindow = "";
var currentTypes = [];
var loader = "";
var $filterType = "";
var $filterList = "";
var $rawData = "";
	
// table repository
var $pTableRows = "";
var $removedRows = [];


// homepage gallery movement
function showGalleryImage(pIndex){
	for(var k=0; k<$('#feature-gallery .item').length; k++){
		if(k!=pIndex){
			$('#feature-gallery .item:eq(' + k + ')').find('.overlay').animate({'height':40},{duration:400,easing:'easeOutExpo',queue:false}).find('span.links').html(newLinks[k]);	
			$('#feature-gallery .item:eq(' + k + ')').find('span.title').html(newTitles[k]);
			$('#feature-gallery .item:eq(' + k + ')').find('span.caption').delay('200').hide();	
		}else{
			if(currImage!=pIndex){ // get rid of jerkiness
				$('#feature-gallery .item:eq(' + k + ')').find('.overlay').animate({'height':80},{duration:400,easing:'easeOutExpo',queue:false}).find('span.links').html(oldLinks[k]);
				$('#feature-gallery .item:eq(' + k + ')').find('span.title').html(oldTitles[k]);
				$('#feature-gallery .item:eq(' + k + ')').find('span.caption').delay('200').show();	
				// swap feature images after delay for 2nd one
				if(pIndex==2){
					fGalTimer = setTimeout(function(){$('#feature-gallery .item:eq(2)').find('div.container').find('img:eq(1)').stop().animate({'opacity':0,duration:400});},1000);
					//$('#feature-gallery .item:eq(2)').find('div.container').find('img:eq(1)').stop().fadeOut(400);
				}else{
					clearTimeout(fGalTimer);
					$('#feature-gallery .item:eq(2)').find('div.container').find('img:eq(1)').stop().animate({'opacity':1,duration:400});	
				}
			}
		}
	}
	currImage = pIndex;
}

// company page team movement
function scrollTeam(pX){
	clearInterval(scrollTeamInterval);
	if(pX!=0){
		scrollTeamInterval = setInterval(function(){doScrollTeam(3*pX);},scrollTeamTime);
	}
}

function doScrollTeam(pX){
	var team = $('#team');
	var teamMembers = team.find('li');
	if(teamMembers.length > 0){
		var teamSize = teamMembers.length;
		var theLeft = team.find('ul').position().left;
		if((theLeft+pX)<38){
			team.find('.control.left').show();	
		}else{
			team.find('.control.left').hide();	
		}
		if((theLeft+pX)>(-teamSize*teamMembers.eq(0).width() - (teamSize)*(Number(teamMembers.eq(0).css('margin-right').substring(0,2))) + 940)){
			team.find('.control.right').show();	
		}else{
			team.find('.control.right').hide();	
		}
		if((theLeft+pX)<38 && (theLeft+pX)>(-teamSize*teamMembers.eq(0).width() - (teamSize)*(Number(teamMembers.eq(0).css('margin-right').substring(0,2))) + 940)){
			team.find('ul').css('left',theLeft+pX);
		}
	}
}

// company page history movement
function scrollHistory(pX){
	clearInterval(scrollHistoryInterval);
	if(pX!=0){
		scrollHistoryInterval = setInterval(function(){doScrollHistory(pX);},scrollHistoryTime);
	}
}

function doScrollHistory(pX){
	var history = $('#history');
	var historyYears = history.find('ul');
	var numYears = historyYears.length;
	if(numYears > 0){
		var theLeft = history.find('table').position().left;
		var theWidth = history.find('table').width();
		if((theLeft+pX)<0){
			history.find('.control.left').show();	
		}else{
			history.find('.control.left').hide();	
		}
		if((theLeft+pX)>(940-theWidth)){
			history.find('.control.right').show();	
		}else{
			history.find('.control.right').hide();	
		}
		if((theLeft+pX)<0 && (theLeft+pX)>(940-theWidth)){
			history.find('table').css('left',theLeft+pX);
		}
	}
}



// property feature transitions
function swapPropFeatures(){
	if(currPropFeature<numPropFeatures-1){
		$('.property-feature li:eq(' + (currPropFeature+1) + ')').css({
			'z-index':numPropFeatures+currPropFeature,
			'opacity':0
		}).animate({
			'opacity':1
		},500);
		currPropFeature++;
	}else{
		$('.property-feature li:not(:last)').css({
			'z-index':0,
			'opacity':0
		})
		$('.property-feature li:last').css({
			'z-index':1
		})
		currPropFeature = 0;
		$('.property-feature li:eq(' + currPropFeature + ')').css({
			'z-index':numPropFeatures+currPropFeature
		}).animate({
			'opacity':1
		},500);
	}
}


// jqm modal window positioning, moves modal to start just below scroll point
var positionModal = function(hash){ 
	var newTop = $(window).scrollTop() + 60;
	hash.w.css('top',newTop).show();
};

// form validation
function validateEmail(pInput){
	$(pInput).css({'background-color': '#ffffff'});
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
   	if(!emailPattern.test($(pInput).val())){
		$(pInput).css({'background-color':'#fe9'});
		return false;
	}else{
		return true;	
	}
}

function validateAtLeast(pInput,pLength){
	$(pInput).css({'background-color': '#ffffff'});
	if($(pInput).attr('value').length<pLength){
		$(pInput).css({'background-color':'#fe9'});
		return false;
	}else{
		return true;	
	}
}




// initialize overlay effects after quicksand sort
function updatePortfolioListOverlays(){
	$('#portfolio-list').find('.overlay').css('opacity',1).mouseenter(function(e){$(this).animate({'opacity':.5},300);}).mouseleave(function(f){$(this).animate({'opacity':1},300)});
}


// filter change
function onFilterChange(e){
	if($(e.target).is(':checked') && $(e.target).attr('id') != $('form.filters input:first').attr('id') && $(e.target).attr('id') != $('form.filters input').eq(1).attr('id')){  // check anything but "select all" or "deselect all"
			if(currentTypes.toString().indexOf($(e.target).val())==-1){
				currentTypes.push($(e.target).val());
				$filterType.eq(1).removeAttr('checked');
			}
		}else if($(e.target).is(':checked') && $(e.target).attr('id')==$('form.filters input').eq(0).attr('id')){ // check "select all"
			$filterType.attr('checked','checked');
			$filterType.eq(1).removeAttr('checked');
			currentTypes = [];
			for(var i=2; i<$filterType.length; i++){
				currentTypes.push($filterType.eq(i).val());	
			}
		}else if($(e.target).is(':checked') && $(e.target).attr('id')==$('form.filters input').eq(1).attr('id')){ // check "deselect all"
			$filterType.removeAttr('checked','checked');
			$filterType.eq(1).attr('checked','checked');
			currentTypes = [];
		}else if($(e.target).attr('id') == $('form.filters input:first').attr('id') || $(e.target).attr('id')==$('form.filters input').eq(1).attr('id')){ // uncheck "select all" or uncheck "deselect all"
			// don't do nothin
		}else{                                                                          						// uncheck anything but "select all" or "deselect all"
			$('form.filters input:first').removeAttr('checked');
			if($('form.filters input:checked').length < 1){
				$('form.filters input').eq(1).attr('checked','checked');	
			}
			var thisType = currentTypes.indexOf($(e.target).val());
			currentTypes.splice(thisType,1);
		}
		
		
		
		// call quicksand on grid
		if($('#portfolio-list').is(':visible')){
			//console.log('grid is visible');
			if(currentTypes.length>0){
				var $filteredData = $rawData.find('li.' + currentTypes.join(', li.'));
			}else{
				var $filteredData = $rawData.find('li.somethingridiculous');
			}
			var $sortedData = $filteredData.sorted({
				by: function(v) {
				  return $(v).attr('data-id');
				}
			});
			$filterList.quicksand($filteredData, {
				adjustHeight:'dynamic',
				duration: 300
			},
			function(){
				updatePortfolioListOverlays();	 // refresh overlays on newly added items
			});	
		}
		
		// add or remove markers from map
		var tempMarkerIndexArray = [];
		var tempTypeNameArray = [];
		
		
		for(var m=0; m<currentTypes.length; m++){
			var thisTypeIndex = $('.filters li input').index($('.filters li input[value="' + currentTypes[m] + '"]'));
			var thisTypeName = $('.filters li').eq(thisTypeIndex).find('label').text(); 
			if(tempTypeNameArray.indexOf(thisTypeName)==-1){
				tempTypeNameArray.push(thisTypeName);	
			}
		}
		
		for(var j=0; j<tempTypeNameArray.length; j++){
			var thisType = tempTypeNameArray[j];
			
			// new matching marker index array
			for(var i=0; i<markerObjectsArray.length; i++){
				var thisMarkerType = markerObjectsArray[i].type;
				if(thisMarkerType.indexOf(thisType) > -1 && tempMarkerIndexArray.indexOf(i)<0){
					tempMarkerIndexArray.push(i);
				}
			}
			
			// re-add removedRows with this data-type
			if($('#portfolio-table').is(':visible')){
				for(var i=0; i<$('#portfolio-table table tbody tr').length; i++){
					var thisRowType = $('#portfolio-table table tbody tr').eq(i).find('td:first').text();
					if(thisRowType.indexOf(thisType) > -1){
						$('#portfolio-table table tbody tr').eq(i).show();
					}
				}
			}
		}
		
		// remove all unnecessary rows
		var toKeep = [];
		var toRemove = [];
		
		
		
		if($('#portfolio-table').is(':visible')){
			//console.log('table is visible');
			
			$('#portfolio-table table tbody tr').each(function(index){
				toRemove.push(index);
			});
			$('#portfolio-table table tbody tr:not(:last)').each(function(zIndex){
				var thisType = $('#portfolio-table table tbody tr:not(:last)').eq(zIndex).find('td:first').text();
				for(var i=0; i<tempTypeNameArray.length; i++){
					if(thisType.indexOf(tempTypeNameArray[i])>-1 && toKeep.indexOf(zIndex)==-1){
						toKeep.push(zIndex);
					}
				}
			});
			
			for(var j=toRemove.length-1; j>=0; j--){
				if(toKeep.indexOf(toRemove[j])==-1){
					$('#portfolio-table table tbody').find('tr:eq(' + toRemove[j] + ')').hide();
				}
			}
			
			for(var j=toKeep.length-1; j>=0; j--){
				$('#portfolio-table table tbody').find('tr:eq(' + toKeep[j] + ')').show();
			}
				
			// update table totals
			updateTableTotals('#portfolio-table');
			
			// trigger table sort again
			$('#portfolio-table').find('table').trigger('update');
			zebraStripe('#portfolio-table table tbody');
		}
		
		// remove all the map markers
		if($('#portfolio-map').is(':visible')){
			//console.log('map is visible');
			for(var l=0; l<markersArray.length; l++){
				if(markersArray[l]!=null) markersArray[l].setMap(null);	
			}
			// then add markers using the temporary marker index array created above
			for(var k=0; k<tempMarkerIndexArray.length; k++){
				var thisMarkerIndex = Number(tempMarkerIndexArray[k]);
				if(markersArray[thisMarkerIndex]!=null) markersArray[thisMarkerIndex].setMap(portfolioMap);
			}
		}
		loader.fadeOut('fast');	
}



// initialize google map
function initializeMap() {
	var image = "";
	// set up all the map markers, add to portfolioMarkers array
	for(var i=0; i<$('form.filters').find('li').length; i++){
		image = new google.maps.MarkerImage('/assets/images/portfolio/map-markers/type' + (i-2) + '.png', new google.maps.Size(22,28), new google.maps.Point(0,0), new google.maps.Point(14,28));
		portfolioMarkers.push(image);
	}
	

	infoWindow = new google.maps.InfoWindow({
		content: ""
	});

	
	var myOptions = {
	  zoom:10,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	portfolioMap = new google.maps.Map(document.getElementById("map-canvas"),
		myOptions);
		
	// loop through locations, add to map
	
	for(var i=0; i<markerObjectsArray.length; i++){
		var typeIndex = 0;
		var typeSplit = markerObjectsArray[i].type.toString().split(', ');
		if(typeSplit && typeSplit.length>1){
			typeIndex = $('.filters li label').index($('.filters').find('li').find('label:contains(' + typeSplit[1] + ')'));
		}else{
			typeIndex = $('.filters li label').index($('.filters').find('li').find('label:contains(' + markerObjectsArray[i].type + ')'));
		}
		
		var thisLatLngArrayString = markerObjectsArray[i].latLng;
		if(thisLatLngArrayString!='null,null'){
			var thisLatLngArray = String(thisLatLngArrayString).split(',');	
			var thisLatLng = new google.maps.LatLng(Number(thisLatLngArray[0]), Number(thisLatLngArray[1]));
		}else{
			var thisLatLng = null;	
		}
		
		var thisShadow = new google.maps.MarkerImage('/assets/images/portfolio/map-markers/shadow.png',
			// The shadow image is larger in the horizontal dimension
			// while the position and offset are the same as for the main image.
			new google.maps.Size(23,28),
			new google.maps.Point(0,0),
			new google.maps.Point(5,18));
		if(markerObjectsArray[i].latLng[0]!='null' && markerObjectsArray[i].latLng[1]!='null'){
			var thisMarker = new google.maps.Marker({
				  position: thisLatLng,
				  icon: portfolioMarkers[typeIndex],
				  shadow: thisShadow
			});
			markersArray.push(thisMarker);
		}else{
			markersArray.push(null);	
		}
	}
	for(var i=0; i<markersArray.length; i++){
		if(markersArray[i]!= null){
			google.maps.event.addListener(markersArray[i], 'click', function(e) {
				var thisObject = markerObjectsArray[markersArray.indexOf(this)];
				var infoString = "<div style='height:80px; width:250px;'>";
				infoString += "<img src='" + thisObject.thumb + "' class='fl' height='52' width='57' />";
				infoString += "<div class='fl' style='width:130px;'>";
				infoString += "<h4><a href='" +  thisObject.permalink + "'>" + thisObject.name + "</a></h4><p style='margin-bottom:0; padding-bottom:10px;'>";
				if(thisObject.street!=''){
					infoString += thisObject.street + "<br />";
				}
				if(thisObject.city!=''){
					infoString += thisObject.city;
				}
				if(thisObject.state!=''){
					if(thisObject.city!='') infoString+= ', ';
					infoString += thisObject.state;	
				}
				infoString+= "<br />";
				
				var typeIndex = 0;
				var typeSplit = thisObject.type.toString().split(', ');
				for(var j=0; j<typeSplit.length; j++){
					typeIndex = $('.filters li label').index($('.filters').find('li').find('label:contains(' + typeSplit[j] + ')'));
					if(j!=0) infoString+=", ";
					infoString+= "<span class='type" + typeIndex + "'>" + typeSplit[j] + "</span>";
				}
				
				infoString += "</p></div><div>";
				infoWindow.setContent(infoString);
				infoWindow.open(portfolioMap,this);
			});
			markersArray[i].setMap(portfolioMap);
		}
	}
			
	portfolioMap.setCenter(latlng);
}




function zebraStripe(pId){
	$(pId).find('tr').removeClass('zebra');
	$(pId).find('tr:not(:hidden,:last)').each(function(index){
		if(index % 2 == 0){
			$(this).addClass('zebra');	
		}
	});
}




function updateTableTotals(pId){
	// table totals
	var $acresTotal = $('#total-portfolio-acres');
	var $rsfTotal = $('#total-portfolio-rsf');
	var $unitsTotal = $('#total-portfolio-units');
	
	var acresTotal = 0;
	var rsfTotal = 0;
	var unitsTotal = 0;
	$(pId).find('tr:not(:hidden)').find('td[data-type="acres"]').each(function(index){
		acresTotal+= ($(this).text()=="" ? 0 : Math.floor(Number($(this).text())));
	});
	$(pId).find('tr:not(:hidden)').find('td[data-type="rsf"]').each(function(index){
		rsfTotal+= ($(this).text()=="" ? 0 : parseInt($(this).text().replace(",","")));
	});
	$(pId).find('tr:not(:hidden)').find('td[data-type="units"]').each(function(index){
		unitsTotal+= ($(this).text()=="" ? 0 : parseInt($(this).text()));
	});
	
	$acresTotal.text(addCommas(acresTotal.toString()) + "+");
	$rsfTotal.text(addCommas(rsfTotal.toString()) + "+");
	$unitsTotal.text(addCommas(unitsTotal.toString()) + "+");	
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


// custom jquery
$(document).ready(function(){
		
	// search term hint
	$('#site-search-term').css('background-position','0 -22px').focus(function(e){
		if($(this).val()==''){
			$(this).css('background-position','0 -22px');
		}
	}).blur(function(e){
		if($(this).val()==''){
			$(this).css('background-position','0 0');	
		}
	}).trigger('blur');
	
	
	// fuckin wordpress man
	$('#reply-title').replaceWith('<h4>Leave a Comment</h4>');
	
	
	// external links in a new window plz
	$('a.external').click(function(event){
		event.preventDefault();
		event.stopPropagation();
		if($(this).attr('href') != "" && $(this).attr('href') != "#"){
        	window.open(this.href, '_blank');
		}
	});
	
	
	// home page | feature-gallery
	// progressive enhancement for js
	oldTitles[3] = $('#feature-gallery').find('.item:last').find('span.title').html() != null ? $('#feature-gallery').find('.item:last').find('span.title').html() : "";
	for(var i=0; i<$('#feature-gallery .item').length; i++){
		oldLinks.push($('#feature-gallery').find('.item:eq(' + i + ')').find('.overlay').find('span.links').html());
	}
	for(var j=0; j<$('#feature-gallery .item').length; j++){
		newLinks.push('<a href="#">Learn More &raquo;</a>');	
	}
	$('#feature-gallery').css({'overflow':'hidden'});
	
	var galleryItems = $('#feature-gallery').find('.item');
	showGalleryImage(0);
	$('#feature-gallery').css({'height':338});
	galleryItems.each(function(index){
		left = (index<2 ? index*516 : left+140);
		// set the overlays at the bottom initially
		if(index>0){
			$('#feature-gallery .item:eq(' + index + ')').find('.overlay').css('height',40);
		}
		$(this).css({'margin':'0','position':'absolute', 'z-index':(index+3), 'left':left}).data('left',left).mouseenter(function(e){
			showGalleryImage(index);
			for(var i=1; i<index; i++){
				$('.item:eq(' + i + ')').animate({'left':($('.item:eq(' + i + ')').data('left')-372) > 0 ? ($('.item:eq(' + i + ')').data('left')-372):0},{duration:300, easing:'easeOutQuad', queue:false});
			}
			$(this).animate({'left':($(this).data('left')-372) > 0 ? ($(this).data('left')-372):0},{duration:300, easing:'easeOutQuad',queue:false});
			for(var j=index+1; j<galleryItems.length; j++){
				$('.item:eq(' + j + ')').animate({'left':$('.item:eq(' + j + ')').data('left')},{duration:300, easing:'easeOutQuad',queue:false});
			}
		});
	});
	
	
	// company page | team member scrolling list
	var team = $('#team');
	var teamList = team.find('ul');
	
	var teamMembers = teamList.find('li');
	if(teamMembers.length > 6){
		teamList.css('left',38);
		team.prepend('<a href="#team-members" title="Scroll Left" class="control left">Left</a><a href="#team-members" title="Scroll Right" class="control right">Right</a>');
		team.find('.control.left').click(function(e){
			e.preventDefault();
		}).mouseenter(function(f){
			scrollTeam(1);
		}).mouseleave(function(g){
			scrollTeam(0);
		});
		team.find('.control.right').click(function(e){
			e.preventDefault();
		}).mouseenter(function(f){
			scrollTeam(-1);
		}).mouseleave(function(g){
			scrollTeam(0);
		});
	}
	teamMembers.mouseenter(function(e){
		$(this).find('.overlay').stop().animate({'bottom':0},{duration:300, easing:'easeOutQuad',queue:false});
	}).mouseleave(function(f){
		$(this).find('.overlay').stop().animate({'bottom':-100},{duration:300, easing:'easeOutQuad',queue:false});
	}).click(function(g){
		$(this).find('a').click();
	});
	
	
	
	
	// company page | history timeline
	$('#history-info').css('opacity',0).show();
	var hAn = 0;
	var history = $('#history');	
	history.prepend('<a href="#history-timeline" title="Scroll Left" class="control left">Left</a><a href="#history-timeline" title="Scroll Right" class="control right">Right</a>');
	history.find('.control.left').click(function(e){
		e.preventDefault();
	}).mouseenter(function(f){
		scrollHistory(1);
	}).mouseleave(function(g){
		scrollHistory(0);
	});
	history.find('.control.right').click(function(e){
		e.preventDefault();
	}).mouseenter(function(f){
		scrollHistory(-1);
	}).mouseleave(function(g){
		scrollHistory(0);
	});
	history.mousemove(function(e){
		var newLeft = Math.floor(e.pageX - history.offset().left) - 40;
		var newTop = Math.floor(e.pageY - history.outerHeight() + $('#history-timeline').outerHeight() - $('#history-info').outerHeight() +10);
		$('#history-info').css({'left':newLeft, 'top':newTop});
	});
	$('#history li a').mouseenter(function(f){
		clearTimeout(hAn);
		$('#history-info').find('p').html($(this).html()).parent().css({'top':-10000}).animate({'opacity':1},{duration:200,queue:false});
	}).mouseleave(function(h){
		hAn = setTimeout(function(){$('#history-info').animate({'opacity':0},{duration:200,queue:false});},250);
	}).click(function(g){
		if($(this).attr('href')=='#' || $(this).attr('href')==''){
			g.preventDefault();
			g.stopPropagation();
		}else{
			g.preventDefault();
			g.stopPropagation();
			if($(this).attr('href') != "" && $(this).attr('href') != "#"){
				window.open($(this).href, '_blank');
			}	
		}
	});
	
	
	
	
	// portfolio page
	updatePortfolioListOverlays();
	
	
	// quicksand sorter
	$filterType = $('form.filters input');
	$filterList = $('.portfolio-list');
	$rawData = $filterList.clone();
	
	// table repository
	$pTableRows = $('#portfolio-table').find('tbody').find('tr:not(:last)');
	$removedRows = [];
	loader = $('.loader');
	loader.css('opacity',.85);
	
	$filterType.change(function(e) {
		loader.show();
		setTimeout(function(){onFilterChange(e)},750);
		// add or delete current types
		
	});
	
	
	
	
	
	
	// portfolio page view type
	$('.gray-box.portfolio').show();
	$('.portfolio-view:not(#portfolio-map)').hide();
	$('#portfolio-view input').removeAttr('checked').change(function(e){
		$('.portfolio-view').hide();
		$('#portfolio-' + e.target.value).show();
		$filterType.eq(0).trigger('change');
		if($('#portfolio-map').is(':visible')){
			loader.css('height',$('#portfolio-map').height() + 10);
			google.maps.event.trigger(portfolioMap, "resize");
			portfolioMap.setCenter(latlng);
		}else if($('#portfolio-table').is(':visible')){
			loader.css('height',$('#portfolio-table').height() + 10);
			zebraStripe('#portfolio-table table tbody');
			updateTableTotals('#portfolio-table');
		}else{
			loader.css('height',$('#portfolio-list').height() + 10);	
		}
	}).eq(0).attr('checked','checked');
	
	
	// portfolio table tablesorter
	var portfolioTable = $('#portfolio-table').find('table');
	portfolioTable.find('tbody').find('tr').each(function(index){
		$(this).find('td:not(:last)').click(function(e){
			window.document.location = $(this).parent().find('td:last').find('a').attr('href');
		});
	});
	var tableHeaders = {};
	tableHeaders[7] = {sorter:'commadigit'}

	portfolioTable.tablesorter({headers:tableHeaders}).bind('sortEnd',function(){zebraStripe('#portfolio-table table tbody')});
	
	
	
	// property page fading feature images
	var thePropFeatures = $('.property-feature ul').find('li');
	if(thePropFeatures.length > 0){
		numPropFeatures = thePropFeatures.length;
		thePropFeatures.each(function(index){
			thePropFeatures.eq(index).css({
				'z-index':numPropFeatures-index,
				'opacity':(index==0 ? 1 : 0)
			});
		});
		thePropFeaturesTimer = setInterval(swapPropFeatures,propFeaturesTime);
	}
	
	
	
	// download form submission
	$('.downloads-form').submit(function(e){
		var errCheck = 0;
		if(!validateEmail('#userEmail')){
			errCheck++;
		}
		var numChecked = 0;
		for(var i=0; i<$('.checkbox').length; i++){
			if($('.checkbox:eq(' + i + ')').attr('checked')){
				numChecked++;
				break;	
			}
		}
		if(errCheck==0 && numChecked>0){
			return true;
		}else{
			return false;	
		}
	});
	
	$('.contact-form').submit(function(e){
		e.preventDefault();
		var errCheck = 0;
		if(!validateAtLeast('#firstName',1)){
			errCheck++;
		}
		if(!validateAtLeast('#lastName',1)){
			errCheck++;
		}
		if(!validateEmail('#userEmail')){
			errCheck++;
		}
		if(!validateAtLeast('#userTitle',1)){
			errCheck++;
		}
		if(!validateAtLeast('#userOrg',1)){
			errCheck++;
		}
		if(!validateAtLeast('#userMessage',1)){
			errCheck++;
		}
		if(errCheck==0){
			$('#contact-submit').attr('disabled','disabled');
			var postString = $(this).serialize();
			$.ajax({
			   type: "POST",
			   url: "send-contact.php",
			   data: postString,
			   success: function(msg){
				 	$('.contact-form').find('input.text').val('');
					$('.contact-form').find('textarea').html('');
					$('.contact-form').find('select').find('option:not(:first)').removeAttr('selected');
					$('#contact-submit').removeAttr('disabled');
					$('h3.first:first').after('<p class="alert">Message received!</p>').next('.alert').delay(5000).fadeOut();
			   }
			});
		}
	});
	
	
	
	// jqmodal windows
	$('.jqmWindow').jqm({onShow:positionModal});
	$('.jqm-trigger').click(function(e){
		e.preventDefault();
		$($(this).attr('href')).jqmShow();
	});
	
	
	
	// page curl and flip
	var curlenter = function(e){
		$(e.target).stop().animate({
			'right':0,
			'top':0
		},300);
	}
	var curlleave = function(f){
		$(f.target).stop().animate({
			'right':'-15px',
			'top':'-15px'
		},300);
	}
	
	$('.msg_block').css('opacity',0);
	$(".pagecurl-trigger").click(function(e){
		e.preventDefault();
		$('#pagecurl').trigger('click');
	});
	$("#pagecurl").bind('mouseenter',curlenter).bind('mouseleave',curlleave).click(function(e) { 
		$('.msg_block').css({'opacity':1,'width':$(window).width()});
		$('#pageflip-content').stop().animate({
			width: $(window).width(),
			height: ($('body').height() > 1224 ? $('body').height() : 1224)
		},200);
		$(this).stop().unbind('mouseenter',curlenter).unbind('mouseleave',curlleave).animate({
			'right':'100%',
			'top':'100%',
			'opacity':0
		},200);
		e.preventDefault();
	});
	$("#pageflip").find('a.return').click(function(e){
		e.preventDefault();
		$('#pageflip-content').stop().animate({
			width: '98px',
			height: '77px'
		},200);
		$('#pagecurl').stop().animate({
			'right':'-15px',
			'top':'-15px',
			'opacity':1
		},200,function(){$(this).bind('mouseenter',curlenter).bind('mouseleave',curlleave)});
		$('.msg_block').stop().delay(100).animate({'opacity':0,'width':'100%'},100);
	});
	
	
	
	
	// update fonts
	Cufon.replace('h3, #utility-nav a', {hover:true});
	
	// move the dotted line underneath h3's if they wrap
	Cufon.CSS.ready(function() {
		$('h3').each(function(index){
			if($(this).height() > 30){
				$(this).css({
					'padding-bottom':'15px',
					'background-position':'left bottom'
				});
			}
		});
	});
	
	
	// initialize map
	if($('#map-canvas').length > 0){
		initializeMap();
		// init case-studies only filter on page load
		if($filterType.length>0){
			$filterType.removeAttr('checked').delay(200).eq(0).attr('checked','checked').trigger('change');	
		}	
	}
	
	// history scroller setup
	var histWidth = $('#history').find('table').width();
	$('#history').find('table').css('left',940-histWidth);
	doScrollTeam(0);
	doScrollHistory(0);
});
























