var map = null;
var hash = "";
if(window.location.hostname=='www.microsoftcambridge.com'){window.location.hostname = 'microsoftcambridge.com';}
$(document).ready(function(){
	if($('.rotate').length > 0)
	{
		var t = setInterval("switchBlocks($('.rotate:visible'))", 15000);
		$('.rotate .heading').click(function() {
			switchBlocks($(this).parent());
			t = clearInterval(t);
		});
	}
	
	//if($('.vevent').length) {
		//$('.vevent').append('<a class="icalendar" target="_blank" title="Download iCalendar" type="text/calendar" href="http://h2vx.com/ics/get-cal.php?uri='+location.href+'">Download ICS File</a>');
	//}
	
	if($('#dnn_RightPane').hasClass('DNNEmptyPane')) {
		$('.content').addClass('full-width');
	}
	
	$("form#Form").submit(function () {
		if($('#txtSearch').length && $('#txtSearch').val()!='') {
			location = '/Search/tabid/722/Default.aspx?search='+$('#txtSearch').val();
			return false;
		}
	});
	
	if($('.teamtwitter').length > 0)
	{
		getTwitters($('.teamtwitter').attr('id'), {
			id: $('.teamtwitter').attr('id'),
			count: 4,
			enableLinks: true,
			ignoreReplies: false,
			clearContents: true,
			template: '%text% <br /><a target="_blank" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
		}); 
	}
	
	if($('#womenstweets').length) {
		$.ajax({
		    url: 'http://search.twitter.com/search.json?q=%23NERDWHM&rpp=3',
		    dataType: 'jsonp',
		    success: function(data) {
		    	$('#womenstweets').html('');
			    $.each(data.results, function(i,result){
		    		$('#womenstweets').append('<div class="tweet"><a href="http://twitter.com/'+result.from_user+'">@'+result.from_user+'</a> '+result.text+'</div>');
			    });
		    }
		});
	}

	if($('#twitter').length > 0)
	{
		
		$('#twitter').append('<h1 id="latest_tweet"><a target="ext" href="http://twitter.com/msnewengland">Latest Tweets</a></h1><div id="tweets"></div><a target="_blank" href="http://twitter.com/msnewengland">Follow Us</a>').css('margin-bottom', '20px');
		
		getTwitters('tweets', {
			id: 'msnewengland',
			count: 2,
			enableLinks: true,
			ignoreReplies: false,
			clearContents: true,
			template: '%text% <br /><a target="_blank" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
		}); 
	}
	
    if($('#blogpreview').length) {
		jQuery.ajax({
	        url: '/blog/site/feed/',
	        dataType: 'xml',
	        success: function(data) {
	            var html = '';
	            /*for(var i = 0; i < feed.items.length && i < 1; i++) {
	                var item = feeds.item[i];
	                html += '<h3>'
	                + '<a href="'
	                + item.link
	                + '">'
	                + item.title
	                + '</a>'
	                + '</h3><small>'
	                + item.pubDate
	                + '</small><p>'
	                + item.description
	                + '</p>';				
	            }*/
	           
	            $(data).find('item:first').each(function() {
	            	var link = $(this).find('link').text();
	            	var title = $(this).find('title').text();
	            	var pubdate = $(this).find('pubDate').text();
	            	pubdate = pubdate.replace(/(.[0-9]):(.*$)/, '');
	            	var description = $(this).find('description').text();
	            	description = description.replace("[...]", '<a href="'+link+'">More...</a>');
	                html += '<div class="blogtitle"><h3>'
	                + '<a href="'
	                + link
	                + '">'
	                + title
	                + '</a>'
	                + '</h3><small>'
	                + pubdate
	                + '</small></div>'
	                + description
	                + '<div class="clear"></div>';
	            });
	            
	            $('#blogpreview').html(html);
	        } 
	    });
    } else {
		jQuery.getFeed({
	        url: '/blog/site/feed/',
	        success: function(feed) {
	            var html = '';
	            for(var i = 0; i < feed.items.length && i < 2; i++) {
	                var item = feed.items[i];
	                html += '<b>'
	                + '<a href="'
	                + item.link
	                + '">'
	                + item.title
	                + '</a>'
	                + '</b><br /><br />';				
	            }
	            $('#blogfeed').html(html);
	        } 
	    });
    }
	
	if($('#msresearchNews').length > 0) {
		var len = 200;
		jQuery.getFeed({
	        url: '/teams/msresearch-news/',
	        success: function(feed) {
	            var html = '<ul>';	            
	            for(var i = 0; i < 3; i++) {
	                var item = feed.items[i];
	                var trunc = item.description;
	                if (trunc.length > len) {
						trunc = trunc.substring(0, len);
						trunc = trunc.replace(/\w+$/, '');
						trunc += '<a href="'+item.link+'">...<\/a>';

					}
	            	var title = item.title;
	                html += '<li><b>'
	                + '<a target="_blank" href="'+item.link+'">'
	                + title
	                + '</a>'
	                + '</b><br />'+trunc+'</li>';				
	            }
	            html += '</ul>';
	            $('#msresearchNews').html(html);
	        } 
	    });
		jQuery.getFeed({
	        url: '/teams/msresearch-publications/',
	        success: function(feed) {
	            var html = '<ul>';	            
	            for(var i = 0; i < 3; i++) {
	                var item = feed.items[i];
	                
	                var trunc = item.description;
	                if (trunc.length > len) {
						trunc = trunc.substring(0, len);
						trunc = trunc.replace(/\w+$/, '');
						trunc += '<a href="'+item.link+'">...<\/a>';

					}
	            	var title = item.title;
	                html += '<li><b>'
	                + '<a target="_blank" href="'+item.link+'">'
	                + title
	                + '</a>'
	                + '</b><br />'+trunc+'</li>';				
	            }
	            html += '</ul>';
	            $('#msresearchPubs').html(html);
	        } 
	    });
	}
	
	if($('#careers').length > 0)
	{
		
		jQuery.getFeed({
	        url: '/jobs/rss/',
	        success: function(feed) {
	            var html = '<ul>';	            
	            for(var i = 0; i < feed.items.length; i++) {
	                var item = feed.items[i];
	            	var title = item.title;
	                html += '<li><b>'
	                + '<a target="_blank" href="'
	                + item.link
	                + '">'
	                + title.replace("(Cambridge, MA, US)", "").replace("Cambridge-","")
	                + '</a>'
	                + '</b></li>';				
					/*var desc = item.description.substring(0, item.description.length-3);
					desc += '<a href="'+item.link+'">...</a>';
	                html += '<div>'
	                + desc
	                + '</div>';*/
	            }
	            html += '</ul>';
	            $('#careers').html(html);
	            $('#careers a').click(function() {
	            	VSLT($(this).attr('href'));
	            });
	        } 
	    });
	}
	
	$("div.menu a img").hover(
		function () {
			if($(this).parent().attr("class")!="active") {
				var url = $(this).attr("src");
				url = url.replace(/.png/, "_ovr.png");
				$(this).attr("src", url);
			}
		},
		function () {
			if($(this).parent().attr("class")!="active") {
				var url = $(this).attr("src");
				url = url.replace(/_ovr/, "");
				$(this).attr("src", url);
			}
		}
	);
	
	var preload_image_object = new Image();
	var image_url = new Array();
	image_url[0] = "about";
	image_url[1] = "events";
	image_url[2] = "people";
	image_url[3] = "teams";
	image_url[4] = "community";
	image_url[5] = "working";
	
	var page = $(".container").attr("id");
	var i = 0;
	for(i=0; i<=5; i++)
	{
		preload_image_object = new Image();
		if(image_url[i] != page)
			preload_image_object.src = "/img/"+page+"/"+image_url[i]+"_ovr.png";
	}
	
	if($('.empvid').length > 0)
	{
		$.getScript('/js/Silverlight.js', function () {
			$(".empvid img").live("click", function() {
				var id = $(this).parent().attr("id");
				var vid = $(this).parent().attr("title");
				var h = 212;
				var w = 380;
				if($(this).parent().hasClass('footer'))
				{
					var h = 156;
					var w = 280;
				}
				else if($(this).parent().hasClass('main'))
				{
					var h = 193;
					var w = 343;
				}
				else if($(this).parent().hasClass('smallbox'))
				{
					var h = 155;
					var w = 280;
				}
				else if($(this).parent().hasClass('comvid'))
				{
					var h = 214;
					var w = 380;
				}
				else if($(this).parent().parent().hasClass('vidright'))
				{
					var h = 158;
					var w = 280;
					
				}
				VSLT(vid);
				insertSLV(id, vid, w, h);
			});
		});
	}
	
	if($('.webcam').length > 0)
	{
		$.getScript('/js/Silverlight.js', function () {
			$(".webcam img").click(function () {
				var id = $(this).parent().attr("id");
				var vid = "http://shared.streamwebtown.com/liveswt";
				webCam(id, vid);
			});
		});
	}
	
	if($('#cambridgemap').length > 0)
	{
		var Boston = new VELatLong(42.36156609702884, -71.08126401901245, 0, VEAltitudeMode.Default);
		getMap(Boston);
		var submitable = false;
		$('#dnn_ctr382_SearchInput_txtSearch').focus(function () {
			submitable = true;
		});
		
		$('#fromadd').focus(function () {
			submitable = false;
		});
		
		$("form").submit( function () {
			if(!submitable)
			{
				getRoute();
				return false;
			}
		});
	}
	
	if($('#massmap').length > 0)
	{
		
		getMassMap();
	}
	
	if($('#community').length > 0)
	{
		slideContent();
		
	}
	
	fixRollovers();
	//alert($('.header').css('width'));
	if($('.header').css('width') == "960px")
	{
		$(window).resize(function() {
			$('.header').css("width", "auto");
		});

	}
	
	if($('#eventsMenu').length > 0)
	{
		slideEvents();
		
		var furl = $('#featured').attr('title');
		var title = $('#dnn_ContentPane h2').text();
		title = title.replace("// ", '');
		var date = $('.dtstart').text();
		
		var fb = '<div class="fbbox"><iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url=http://'+location.host+encodeURI(furl)+'&text='+title+' '+date+'" style="width:100px; height:20px;"></iframe><iframe src="http://www.facebook.com/plugins/like.php?href=http://'+location.host+encodeURI(furl)+'&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true"></iframe></div>';
		
		$('#featured').prev().before(fb);
	}
	
	if($('.featuredorg').length)
	{
		$('.orglist li>a').click(function() {
			$('.featuredorg').html($(this).next('div').html());
			return false;
		});
	}
	
	if($('.descriptions').length)
	{
		hash = "#working";
		if(window.location.hash!="")
		{
			hash = window.location.hash;
			$(hash).css('background-color', 'white');
		}
		
		$('.descriptions div').after('<a href="#">Read More...</a>');
		$('.descriptions a').live("click", function() {
			if($(this).prev('div').css('display')=='none')
			{
				$(this).text('Read Less...');
			}
			else
			{
				$(this).text('Read More...');
			}
			$(this).prev('div').toggle();
			
			return false;
		});
		$(hash).focus().next().next('div').show().next('a').text('Read Less...');
		
		
	}
	slideDirections();
	
});


function switchBlocks(block)
{
	block.parent().css('background-image','url(/img/teams/contentpane_back.png)');
	block.fadeOut('slow', function() {
		block.siblings().fadeIn('slow', function() {
			block.parent().css('background-image','none');
		});
	});
}

function slideEvents()
{
	$('#toArchive').click(function () {
		$('#eventsMenu').animate({ 
			left: "-300px"
			}, 500, function () {
			$('.archLabel:first, .archiveCell .eventtab:first-child').next().slideDown();
		});
		return false;
	});
	
	$('#toUpcoming').click(function () {
		$('.archLabel, .archiveCell .eventtab').next().slideUp();
		$('#eventsMenu').animate({ 
			left: "0px"
			}, 500 );
		return false;
	});
	
	$('.archLabel').click(function () {
		$(this).next().slideToggle();
	});
	
	$('.eventbody a.eventtab').click(function() {
		$(this).next('.group').slideToggle();
	}).each(function() {
		$(this).next('.group').hide();
	});
	$('.eventbody a.eventtab:first-child').next('.group').show();
	$('.group .here').parent().show();
}

function insertSLV(id, vid, w, h)
{
	Silverlight.createObject(
		"/media/VideoPlayer.xap",
		document.getElementById(id),
		"slPlugin",
		{
			width: w, height: h, background: "white", 
			version:"2.0.31005.0"
		},
		{  },
		"autostart=true,cc=true,markers=false,m="+vid, 
		"context"
	);
}

function webCam(id, vid)
{
	Silverlight.createObject(
		"/media/VideoPlayer.xap",
		document.getElementById(id),
		"slPlugin",
		{
			width: "276", height: "155", background: "white", 
			version:"2.0.31005.0"
		},
		{  },
		"autostart=true,cc=true,markers=false,m="+vid, 
		"context"
	);
}


function getMassMap()
{
	var LatLong = new VELatLong(42.36156609702884, -71.08126401901245, 0, VEAltitudeMode.Default);
	var map = new VEMap('massmap');
	map.LoadMap(LatLong, 8);
	
	var cambridgeLL = new VELatLong(42.36156609702884, -71.08126401901245, 0, VEAltitudeMode.Default);
	var cambridge = new VEShape(VEShapeType.Pushpin, cambridgeLL);
	cambridge.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	cambridge.SetTitle("<div class=\"pinTitle\">Microsoft New England Research & Development Center</div>");
	cambridge.SetDescription("<div class=\"pinDetails\">One Memorial Drive <br /> Suite 100 <br /> Cambridge, MA 02142 <br /> Tel: (857) 453-6000 <br /> Fax: (857) 453-6013</div>");
	map.AddShape(cambridge);
	
	/*var navicLL = new VELatLong(42.37450635546363, -71.271, 0, VEAltitudeMode.Default);
	var navic = new VEShape(VEShapeType.Pushpin, navicLL);
	navic.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	navic.SetTitle("<div class=\"pinTitle\">Navic Networks</div>");
	navic.SetDescription("<div class=\"pinDetails\">201 Jones Rd.<br /> Waltham, MA 02451 <br /> Phone: (781) 398-4600 <br /> Fax: (781) 398-4601</div>");
	map.AddShape(navic);*/
	
	/*var districtLL = new VELatLong(42.37550635546363, -71.272, 0, VEAltitudeMode.Default);
	var district = new VEShape(VEShapeType.Pushpin, districtLL);
	district.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	district.SetTitle("<div class=\"pinTitle\">Microsoft Northeast District Office & FAST Search & Transfer</div>");
	district.SetDescription("<div class=\"pinDetails\">201 Jones Rd.<br /> Sixth Floor <br /> Waltham, MA 02451 <br /> Phone: (781) 487-6400 <br /> Fax: (781) 487-6600</div>");
	map.AddShape(district);*/
	
	var techcLL = new VELatLong(42.40539438826585, -71.27953290939331, 0, VEAltitudeMode.Default);
	var techc = new VEShape(VEShapeType.Pushpin, techcLL);
	techc.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	techc.SetTitle("<div class=\"pinTitle\">Microsoft Technology Center: Boston</div>");
	techc.SetDescription("<div class=\"pinDetails\">890 Winter Street <br />Suite 100<br />Waltham, MA 02451 <br /> Phone: (781) 522-7900</div>");
	map.AddShape(techc);
	
	/*var fastLL = new VELatLong(42.37550635546363, -71.271, 0, VEAltitudeMode.Default);
	var fast = new VEShape(VEShapeType.Pushpin, fastLL);
	fast.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	fast.SetTitle("<div class=\"pinTitle\">FAST Search & Transfer (Microsoft Subsidiary)</div>");
	fast.SetDescription("<div class=\"pinDetails\">201 Jones Road <br /> Sixth Floor <br />Waltham, MA 02451 <br /> Phone: (781) 487-6400 <br /> Fax: (781) 487-6600</div>");
	map.AddShape(fast);*/
	
	var sentillLL = new VELatLong(42.6869229, -71.2125849, 0, VEAltitudeMode.Default);
	var sentill = new VEShape(VEShapeType.Pushpin, sentillLL);
	sentill.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	sentill.SetTitle("<div class=\"pinTitle\">Sentillion (a Microsoft Company)</div>");
	sentill.SetDescription("<div class=\"pinDetails\">40 Shattuck Rd. <br />Suite 200 <br />Andover, MA 01810 <br /> Phone: (978) 689-9095</div>");
	map.AddShape(sentill);
	
	/*var razorfishLL = new VELatLong(42.36231723428565, -71.08171463012695, 0, VEAltitudeMode.Default);
	var razorfish = new VEShape(VEShapeType.Pushpin, razorfishLL);
	razorfish.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	razorfish.SetTitle("<div class=\"pinTitle\">Razorfish (Microsoft Subsidiary)</div>");
	razorfish.SetDescription("<div class=\"pinDetails\">101 Main St <br />Cambridge, MA 02142 <br /> Phone: (617) 250-2500</div>");
	map.AddShape(razorfish);*/
	
	/*var grooveLL = new VELatLong(42.55901428173032, -70.88705062866211, 0, VEAltitudeMode.Default);
	var groove = new VEShape(VEShapeType.Pushpin, grooveLL);
	groove.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>");
	groove.SetTitle("<div class=\"pinTitle\">Microsoft Groove</div>");
	groove.SetDescription("<div class=\"pinDetails\">100 Cummings Center <br /> Suite 535Q <br />Beverly, MA 01915 <br /> Phone: (978) 720-2000</div>");
	map.AddShape(groove);*/
}

function myRouteHandler(route)
{
	var turns = "<h2>Turn-by-Turn Directions</h2>(rounding errors are possible)";
	turns += "<p><b>Distance:</b> " + route.Distance.toFixed(1) + " miles</p>";
		// Unroll route and populate DIV
		var legs			 = route.RouteLegs;
		var leg			 = null;
		var turnNum		 = 0;	// The turn #

		// Get intermediate legs
		for(var i = 0; i < legs.length; i++)
		{
			// Get this leg so we don't have to derefernce multiple times
			leg = legs[i];	// Leg is a VERouteLeg object
			var legNum = i + 1;
			

			// Unroll each intermediate leg
			var turn			= null;	 // The itinerary leg
			var legDistance = null;	 // The distance for this leg
			
			for(var j = 0; j < leg.Itinerary.Items.length; j ++)
			{
				turnNum++;
				turn = leg.Itinerary.Items[j];	 // turn is a VERouteItineraryItem object
				turns += "<b>" + turnNum + ".</b>\t" + turn.Text;
				legDistance	= turn.Distance;

				 // So we don't show 0.0 for the arrival
				if(legDistance.toFixed(1) > 0)
				{
					// Round distances to 1/10ths
					turns += " (" + legDistance.toFixed(1) + " miles)";
	
				}
				turns += "<br/>";
			}
			

		// Populate DIV with directions
		$("#instructions").html(turns);
	}

}

function getRoute()
{
	var origin = $("#fromadd").attr('value');
	var options = new VERouteOptions();
	options.SetBestMapView = true;
	options.RouteCallback = myRouteHandler;
	var locations = new Array(origin, (new VELatLong(42.3615, -71.08126401901245, 0, VEAltitudeMode.Default)));
	$("#instructions").html('<p style="text-align: center;"><img src="/img/loading.gif" alt="loading..."/></p>');
	$("#instructions").slideDown();
	map.GetDirections(locations, options);
	return false;
}

function getMap(Boston)
{
	
	map = new VEMap('cambridgemap');
	map.LoadMap(Boston, 14);
	var shape = new VEShape(VEShapeType.Pushpin, Boston);
	shape.SetCustomIcon("<img src=\"/Portals/0/pushpin.png\"/>"); // if you wanted to set a custom icon
	shape.SetTitle("<div class=\"pinTitle\">Microsoft New England Research & Development Center</div>");
	shape.SetDescription("<div class=\"pinDetails\">One Memorial Drive <br /> Cambridge, MA 02142 <br /> Tel: (857)453-6000</div>");
	map.AddShape(shape);
}

function fixRollovers()
{
	$('.empbox p a').each(
		function ()
		{
			if(window.location.pathname == $(this).attr('href'))
			{
				$(this).parent().parent().addClass('here');
			}
		}
	);
	
	$('.eventbox p a').each(
		function ()
		{
			if(window.location.pathname == $(this).attr('href'))
			{
				$(this).parent().parent().addClass('here');
			}
		}
	);
	
	$('#teams #dnn_RightPane a').each(
		function ()
		{
			if(window.location.pathname == $(this).attr('href'))
			{
				$(this).children().addClass('here');
			}
		}
	);
	
	if($('#featured').length > 0)
	{
		var path = $('#featured').attr('title');
		//$('#featured').attr('title', '');
		$('.eventbox p a').each(
			function ()
			{
				if(path == $(this).attr('href'))
				{
					$(this).parent().parent().addClass('here');
				}
			}
		);
		
		$('.empbox p a').each(
			function ()
			{
				if(path == $(this).attr('href'))
				{
					$(this).parent().parent().addClass('here');
				}
			}
		);
		
		$('#teams #dnn_RightPane a').each(
			function ()
			{
				if(path == $(this).attr('href'))
				{
					$(this).children().addClass('here');
				}
			}
		);
	}
	
	if($('.archiveCell .here').length > 0)
	{
		$('#eventsMenu').css('left', '-300px');
		$('.archiveCell .here').parent().css('display', 'block');
	}
	
	
}

function slideContent()
{
	$("h2.down").click(function ()
	{
		$(this).next("div").toggle("fold", {direction: "up"}, 500, function ()
		{
			$(this).removeAttr("style");
			$(this).toggleClass("hidden");
		});
		$(this).toggleClass("arrow");
	});
}

function slideDirections()
{
	$("h3.dir").next("ol").hide().addClass("hidden");;
	$("h3.dir").click(function ()
	{
		$(this).next("ol").toggle("fold", {direction: "up"}, 500, function ()
		{
			$(this).removeAttr("style");
			$(this).toggleClass("hidden");
		});
	});	
}
