$(document).ready(function() {
	loadContent();
	backtoProjects();
	backtoTop();
	$('div.showcase-container').css('display', 'none');
	//mainNavAjaxLoad();
	//homeAjaxLoad();
		// Hide all content text
	$('ul.open-close-list li ul,ul.open-close-hover-list li ul').css('display', 'none');
	weThinkList();
	setBlogFilter();
	jQuery.easing.def = 'easeOutExpo';

	if ($('div.random-tout-container').length || $('p.news').length) {
		// Load random tout xml file
		$.ajax({
			type: "GET",
			url: "/common/xml/touts.xml",
			dataType: "xml",
			success: parseXML
		});
	}

	if ($('#twitter').length) {
		$("#twitter").getTwitter({
			userName: "viewstudio",
			numTweets: 15,
			loaderText: "Loading tweets...",
			slideIn: true,
			showHeading: true,
			headingText: "View Studio Twitter",
			showProfileLink: true
		});
	}
	
	if ($('#map').length) {
		setMap();
		
	}

});

function parseXML(xml){
	$('div.random-tout-container, p.news, ul.newslink li a').html('');

	$ajaxTout = $(xml).find('tout');

	$ajaxTout.each(function(index, element){

		$ajaxHeading = $(this).find('heading').text();
		$ajaxSubHeading = $(this).find('subheading').text();
		$ajaxParagraph = $(this).find('paragraph').text();
		$ajaxLink = $(this).find('linktext').text();
		$ajaxURL = $(this).find('linkurl').text();
		$ajaxNewsLink = $(this).find('newslink').text();
		$ajaxNewsLinkText = $(this).find('newslinktext').text();
		$ajaxTarget = $(this).find('target').text();
		
		$ajaxHTML = '<div class="tout" id="ajax-tout' + index + '"><h3>' + $ajaxHeading + '</h3><h4>' + 
					$ajaxSubHeading + '</h4><p>' + $ajaxParagraph + '</p><ul><li><a href="' + $ajaxURL + '">' + $ajaxLink + '</a></li></ul></div>';
		
		$('div.random-tout-container').append($ajaxHTML);
		$('div.random-tout-container #ajax-tout0').addClass('active');
		if(index < 1){
			$('p.news').append($ajaxSubHeading);
			$('ul.newslink li a').append('<a href="' + $ajaxNewsLink + '" title="' + $ajaxSubHeading + '" target="' + $ajaxTarget + '">' + $ajaxNewsLinkText + '</a>');
		}

	});
	
	$('div.random-tout-container div.tout').css('opacity', 0.0);
	$('div.random-tout-container div.tout.active').css('opacity', 1.0);

	$toutFadeInterval = setInterval( 'ajaxToutSwitch()', 4000 );

	$('div.random-tout-container div.tout').mouseover(function(e){
		clearInterval($toutFadeInterval);
	});
	
	$('div.random-tout-container div.tout').mouseout(function(){
		$toutFadeInterval = setInterval( 'ajaxToutSwitch()', 4000 );
	});
}

function ajaxToutSwitch() {
    var $active = $('div.random-tout-container div.active');

    //if ( $active.length == 0 ) $active = $('div.random-tout-container div:last');
	if ( $active.length == 0 ) $active = $('div.random-tout-container #ajax-tout' + ($ajaxTout.length-1));

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        //: $('div.random-tout-container div:first');
		: $('div.random-tout-container #ajax-tout0');

    // uncomment the 3 lines below to pull the images in random order
    
    var $sibs  = $active.siblings();
    var rndNum = Math.floor(Math.random() * $sibs.length );
    var $next  = $( $sibs[ rndNum ] );


    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2200, function() {
            $active.removeClass('active last-active');
    });
}

function loadContent(){	
	$('div.project-container div.row div').click(function() {
		$ajaxHREF = $(this).children('a').attr('href');
		$('div.project-container div.row div').removeClass('active');
		$(this).addClass('active');
		$('div.showcase-container').load($ajaxHREF + ' div.showcase', function() {
			revealContent();
			$('div.footer-left').css('display', 'block');
			$('div.footer-middle').css('display', 'block');
		});
		return false;
	});
	
	$('div.header-right ul li a.showcase-link').click(function() {
		$ajaxHREF = $(this).attr('href');
		$('div.showcase-container').load($ajaxHREF + ' div.showcase', function() {
			revealContent();
			$('div.footer-left').css('display', 'none');
			$('div.footer-middle').css('display', 'none');
		});
		return false;
	});
}

function revealContent(){
	$('div.showcase-container').slideDown('fast', 
		function() {
			addLoadingBox();
			$('div.showcase-container').onImagesLoad({ 
                selectorCallback: allImageSectionsLoaded 
            }); 
		});
	$('div.backto-projects').fadeIn('slow');
	$('div.backto-top').fadeIn('slow');
	backtoTop();
}

function backtoProjects(){
	$('div.backto-projects a').click(function(){
			// Calculate the top offset of the element
			$targetOffset = $('body').offset();
			$targetTop = $targetOffset.top;
			
			//Slide to the element by setting the body scroll top to anchor top
			$('html, body').animate({scrollTop:$targetTop}, 'slow', 'easeOutExpo');
		return false;
	});
	
}

function backtoTop(){
	$('div.backto-top a').click(function(){
			// Calculate the top offset of the element
			$targetOffset = $('#target').offset();
			$targetTop = $targetOffset.top;
			
			//Slide to the element by setting the body scroll top to anchor top
			$('html, body').animate({scrollTop:$targetTop}, 'slow', 'easeOutExpo');
		return false;
	});
	
}
 
function allImageSectionsLoaded($selector){
	$('img.loader').remove(); 
	$('#pre-loaderbox').fadeOut('slow',
		function() {
			$('#pre-loaderbox').remove();
			$('img.loader').remove();
			// Calculate the top offset of the flash footer
			$targetOffset = $('#target').offset();
			$targetTop = $targetOffset.top;
			
			//Slide to the flash footer by setting the body scroll top to anchor top
			$('html, body').animate({scrollTop:$targetTop}, 'slow', 'easeOutExpo');
		});
} 

function addLoadingBox(){
	$('body').prepend('<div id=\'pre-loaderbox\'></div>');
	$('#pre-loaderbox').css('display', 'none');
	$('#pre-loaderbox').css('width', '100%');
	$pageHeight = $(document).height();
	$('#pre-loaderbox').css('height', $pageHeight);
	$('#pre-loaderbox').css('z-index', '12');
	$('#pre-loaderbox').css('position', 'absolute');
	$('#pre-loaderbox').css('background', '#000000');
	$('#pre-loaderbox').css('opacity', '0.5');
	$('#pre-loaderbox').fadeIn('slow',
		function() {	
			$('<img class=\'loader\' src=\'/common/images/ajax-loader.gif\'/>').insertAfter('#pre-loaderbox');
			$('img.loader').css('position', 'absolute');
			$('img.loader').css('z-index', '14');

			$top = (($(window).height() - 15) / 2) + $(window).scrollTop();

			$left = ($('body').outerWidth() - 128) / 2;
			$('img.loader').css('top', $top);
			$('img.loader').css('left', $left);
		});
}

function weThinkList(){

	$weThinkLinks = $('ul.open-close-list li').find('a');
	
	// Open the first item and set to active
	$weThinkLinks.eq(0).parent().attr('class', 'active');
	$weThinkLinks.eq(0).parent().find('ul').slideDown('slow', 'easeOutExpo');
	
	// Create click event to show and hide content
	$weThinkLinks.click(function(){
		// If item is already active and clicked - close it
		if($(this).parent().attr('class') == 'active'){
			$('ul.open-close-list li.active ul').slideUp('slow', 'easeOutExpo');
			$('ul.open-close-list li').removeClass('active');
		}
		// Else open 
		else{
			if($('ul.open-close-list').find('li.active').length == 0){
				$(this).parent().addClass('active');
				$(this).parent().find('ul').slideDown('slow', 'easeOutExpo');	
			}
			else{
				$('ul.open-close-list li.active ul').slideUp('slow');
				$('ul.open-close-list li').removeClass('active');
				$(this).parent().addClass('active');
				$(this).parent().find('ul').slideDown('slow', 'easeOutExpo');
			}
		}
	});
}

/*function mainNavAjaxLoad(){
	$mainNavLinks = $('div.main-navigation ul li').find('a');

	$mainNavLinks.click(function(){
		$ajaxHREF = $(this).attr('href');
		if($(this).attr('class') == 'active'){
			return false;	
		}
		else{
			$mainNavLinks.removeClass('active');
			$(this).addClass('active');
			$('div.main-content, div.footer').fadeOut('slow', function() {
				$('#container').load($ajaxHREF + ' div.main-content', function() {
					$('div.main-content').css('display', 'none');
					fadeContent();
				});
			});
			return false;
		}
	});
}

function homeAjaxLoad(){
	$homeLink = $('h1').find('a');
	$mainNavLinks = $('div.main-navigation ul li').find('a');

	$homeLink.click(function(){
		$ajaxHREF = $(this).attr('href');
		$('div.main-content, div.footer').fadeOut('slow', function() {
			$('#container').load($ajaxHREF + ' div.main-content', function() {
				$('div.main-content').css('display', 'none');
				fadeContent();
			});
		});
		return false;
	});	
}

function fadeContent(){
	$('div.main-content, div.footer').fadeIn('slow');
	weThinkList();
	$('div.showcase-container').css('display', 'none');
	loadContent();
	backtoProjects();
	backtoTop();
	setBlogFilter();
}*/

function setBlogFilter(){

	$filterLink = $('div.blog-filter').find('a');
	
	$filterLink.click(function(){
		$filter = $(this).html();
		$filterLink.parent().removeClass('active');
		$(this).parent().addClass('active');
		
		$blogHeading = $('div.blog-container').find('h2');
		$blogHeading.each(function(index, element){
			if($filter == 'View All'){
				$(element).parent().css('display', 'block');
				
				$('div.twitter-blog').each(function(index, element){
					if (index > 2){
						$(element).hide();
					}
					else{
						$(element).show();
					}
				});
			}
			else{
				if($(element).html() == $filter){
					$(element).parent().css('display', 'block');	
				}
				else{
					$(element).parent().css('display', 'none');
				}
			}
		});
	});
	
	$loc = window.location + "";
	$pos = $loc.indexOf('?');

	if($pos != -1){
		$loc = $loc.substring($pos + 1);
		//alert($loc);
		//alert($pos);
		$filterLink = $('div.blog-filter').find('a');

		$('div.blog-filter').find('li').removeClass('active');

		$filterLink.each(function(index, element){
			if($(this).html() == $loc){
				$(this).parent().addClass('active');
			}
		});
		

		$blogHeading = $('div.blog-container').find('h2');
		$blogHeading.each(function(index, element){
			if($(element).html() == $loc){
				$(element).parent().css('display', 'block');	
			}
			else{
				$(element).parent().css('display', 'none');
			}
		});
		
	}
	else{
		return false;
	}
}


// Tweet Functions

function populateTweetBlog(){
	$("ul#twitter_update_list li").each(function(index, element){
		$tweetText = $(element).find('span').html();
		$tweetTime = $(element).children().eq(1).html();
		$blogDiv = $('div.blog-container').children().eq(2);
		if ($('a.follow').length){
			if (index < 1){
				$('p.tweet').append($tweetText);
			}
			$('p.tweet a').attr('target', '_blank');
		}
		else{
			if (index < 3){
				$blogDiv = $('div.blog-container').children().eq(2 + index);
				$('<div class="blog-item twitter-blog"><h2>Tweets</h2><h3>' + $tweetText + '</h3><p>' + $tweetTime + '</p></div>').insertBefore($blogDiv).show();
			}
			else {
				$('div.blog-container').append('<div class="blog-item twitter-blog"><h2>Tweets</h2><h3>' + $tweetText + '</h3><p>' + $tweetTime + '</p></div>');
			}

			$('div.twitter-blog a').attr('target', '_blank');
		}
	});	
}

// Map Function

/*function setMap(myLatitude, myLongitude){    
    if (GBrowserIsCompatible()) { 

      // A function to create the marker and set up the event window
      // Dont try to unroll this function. It has to be here for the function closure
      // Each instance of the function preserves the contends of a different instance
      // of the "marker" and "html" variables which will be needed later when the event triggers.    
      function createMarker(point,html) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
      }

      // Display the map, with some controls and set the initial location 
      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(51.501876, -0.250977),15);
    
      // Set up three markers with info windows 
    
      var point = new GLatLng(myLatitude,myLongitude);
      var marker = createMarker(point,'<div class="map-logo"><img src="http://www.viewplc.com/common/images/logo-view.gif"><br \/><br \/><br \/>' +
	'The Penthouse, Long Island House, 1-4 Warple Way<br \/> London W3 0RG<br \/> 020 8740 9751<\/div>')
      map.addOverlay(marker);

    }
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}*/

var latlng = new google.maps.LatLng(51.501856, -0.252577);
var viewLoc = new google.maps.LatLng(51.504176, -0.255477);

function setMap() {
    var myOptions = {
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
	var map = new google.maps.Map(document.getElementById("map"),
        myOptions);

	var marker = new google.maps.Marker({
		position: viewLoc, 
		map: map, 
		title:"View PLC"
	});

	var contentString = '<div class="map-logo"><img src="http://www.viewplc.com/common/images/logo-view.gif"><br \/><br \/><br \/>'+
    'The Penthouse, Long Island House, 1-4 Warple Way<br \/> London W3 0RG<br \/> 020 8740 9751<\/div>';

	var infowindow = new google.maps.InfoWindow({
    content: contentString
	});

	google.maps.event.addListener(marker, 'click', function() {
	infowindow.open(map,marker);
	});

	var homeControlDiv = document.createElement('DIV');
	var homeControl = new HomeControl(homeControlDiv, map);

	homeControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(homeControlDiv);

}

function HomeControl(controlDiv, map) {

	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '5px';

	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.width = '78px'
	controlUI.style.height = '26px'
	controlUI.style.backgroundImage = 'url(common/images/logo-view-trans.gif)';
	controlUI.style.cursor = 'pointer';
	controlUI.title = 'Click to return to View';
	controlDiv.appendChild(controlUI);

	// Setup the click event listeners: simply set the map to
	// Chicago
	google.maps.event.addDomListener(controlUI, 'click', function() {
		map.setCenter(viewLoc)
	});
}
