///////////////////////////////////////
// Run at DOM load
///////////////////////////////////////
	
$(window).load(function() { 
	
	// Set up mobile scrolling
	mobileScroll(); 
	
	// Copyright Fix
	copyrightFix();	

	// Updates on orientation change (mobile)
	if (userAgent != 'other') {
		window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', orientationUpdate, false);
	}

	// Style for unify
	if (top != self) {
		unifyStyling();
	}

	if ($('body').hasClass('home')) {
		// Optional homepage news
		homepageNews();
	}
	
	if ($('body').hasClass('portfolio')) {
		// Set the correct height of the portfolio container
		portfolioHeight();
		// Reset the correct height when the width of the browser changes (ie, orientation change)
		$(window).resize(function() {
			portfolioHeight();
		});
		// Enable portfolio sliding
		portfolioScroll();
		
		// Enable portfolio details
		portfolioDetail();
	}
	
	if ($('body').hasClass('team')) {
		// Enable team details
		teamDetail();
	}
	
	// Last news item border removal
	if ($('body').hasClass('news')) {
		$('li:last', '#news-list').css('border', 'none');
	}
});

///////////////////////////////////////
// Mobile Scrolling
///////////////////////////////////////

function mobileScroll() {
	if(userAgent != 'other') {	
		delay = setTimeout(function() {
			headerH = $('header').height();
	   		footerH = $('footer').height();
	   		$('#content').css('height', ($(document).height() - headerH - footerH));
			$('#scroller').touchScroll();
			clearTimeout(delay);
		}, 100);
	}
}

/*////////////////////////////////*/
/* Copyright Fix */
/*////////////////////////////////*/
var copyMoved = false;

function copyrightFix() {	
	headerH = $('header').height();
	footerH = $('footer').height();
	if (userAgent == 'other') {
		if ($('#wrapper').height() < $(window).height()) {
			$('.copy').css('position', 'fixed').css('bottom', '65px');
		}
	}
	else {
		if (!copyMoved) {
			// Mobile, move copyright to #content			
			copyHTML = $('.copy').html();
			$('.copy').remove();
			$('#scroller').append('<div class="copy">' + copyHTML + '</div>');
			copyMoved == true;		
		}
		if ($('#wrapper').height() < ($(document).height() - headerH - footerH)) {
			$('.copy').css('position', 'absolute').css('bottom', '0');
		}
	}
}

///////////////////////////////////////
// Orientation Update
///////////////////////////////////////

function orientationUpdate() {
	mobileScroll(); 
	$('#scroller').touchScroll('setPosition', 0);
	copyrightFix();	
	
	// Update portfolio slide 
	containerWidth = $('#portfolio-container').width();
}

///////////////////////////////////////
// Unify Styling
///////////////////////////////////////

function unifyStyling() {	
	$('header').hide();
	$('#footer').hide();
	$('#homepage-news').show();
	$('.copy').hide();
	$('#content').css('padding-top', '20px');
	
	// Portfolio
	$('a#slide-left').css('background', 'none').css('padding-right', '0').css('cursor', 'default');
	$('a#slide-right').css('background', 'none').css('padding-left', '0').css('cursor', 'default').css('float', 'right');
	
	// Team
/*
	$('#team-list li').css('width', '29%');
	$('ul#team-list li .img-container').css('background', 'none');
	$('.team-wrapper').prepend('<span style="width: 96%; padding: 0 2%;">*Layout adjusted to 3 columns for easier Unify editing</span>');
*/
}

///////////////////////////////////////
// Configure Shadowbox 
///////////////////////////////////////
if (typeof Shadowbox != 'undefined') {
	Shadowbox.init({
	    skipSetup: true
	});
}

///////////////////////////////////////
// Homepage News
///////////////////////////////////////

function homepageNews() {
	if ($('.news-content:has(*)', '#homepage-news').length > 0) {
		$('#content').addClass('show-news');
		$('#homepage-news').prepend('<h4>Latest News</h4>');
	}
}


///////////////////////////////////////
// Portfolio Height
///////////////////////////////////////
function portfolioHeight() {
	// Get height of div.set
	var setHeight = $('div.set').height();
	// Apply this height to its container
	$('div#portfolio-container').css('height', setHeight);	
}

///////////////////////////////////////
// Portfolio Scroll
///////////////////////////////////////

function portfolioScroll() {
	containerWidth = $('#portfolio-container').width(); 
	
	if (screen.width > 480 && top === self) {
		$('#content').addClass('full-featured');
		$('#slide-right').hide();
		
		// Slide Portfolio Left to show Softbank Corp Portfolio
		$('a#slide-left').click(function(){
			$('#slide-right').delay(100).show();
			$('#set-1').animate({ left: '-' + containerWidth});
			$('#set-2').show().animate({ left: '0' }, 400, function() {
				$('#slide-left').hide();
			});
	
			return false;
		});
		// Slide Portfolio Right to show Softbank Capital Portfolio
		$('a#slide-right').click(function(){
			$('#slide-left').delay(100).show();
			$('#set-2').animate({ left: '960px' });
			$('#set-1').animate({ left: '0'}, 400, function() {
				$('#slide-right').hide();
			});
			return false;
		});
	}
	else if (userAgent != 'other') {
		$('#set-2').hide()
		$('a#slide-left').click(function(){
			$('#set-1').fadeOut(200, function() {
				$('#set-2').fadeIn(200);			
			});
		});
		$('a#slide-right').click(function(){
			$('#set-2').fadeOut(200, function() {
				$('#set-1').fadeIn(200);			
			});
		});
		
	}
	else {
		//$('ul.portfolio-list').unwrap();
		$('a#slide-left').text('Softbank Capital Portfolio');
		$('a#slide-right').text('Select SOFTBANK Group Portfolio');
		$('a#slide-left img, a#slide-right img').css('display', 'none');	
	}
}


///////////////////////////////////////
// Modals
///////////////////////////////////////

// Variables
var portfolioCompanies = [];
var corporateCompanies = [];
var portfolioData = {};
var portfolioTemplate = '<div id="portfolio-modal">' + 
	'<div id="modal-heading">' +
	'<a onclick="Shadowbox.close()" class="close">Close</a>' +
	'<h2></h2>' +
	'<div class="prev-next"><a class="prev">Prev</a><a class="next">Next</a></div>' + 
	'<div class="clearit"></div>' +
	'</div>'+	
	'<div id="modal-content"></div>' +
	'</div>';

var teamMembers = [];
var teamData = {};	
var teamTemplate = '<div id="team-modal">' + 
	'<div id="modal-heading">' +
	'<a onclick="Shadowbox.close()" class="close">Close</a>' +
	'<h2></h2>' +
	'<div class="prev-next"><a class="prev">Prev</a><a class="next">Next</a></div>' + 
	'<div class="clearit"></div>' +
	'</div>'+	
	'<div id="modal-content"></div>' +
	'<a id="print" onClick="printModal()"><img src="images/layout/print.png" alt="Print" /> Print</a>' + 
	'</div>';

function portfolioDetail() {
	if ($('body').width() > 700) {
		$('.portfolio-list a', '#set-1').each(function() {
			portfolioCompanies.push($(this).attr('href'));
			$(this).triggerModal('portfolio', $('.portfolio-list a', '#set-1').index($(this)));
		});
		
		$('.portfolio-list a', '#set-2').each(function() {
			corporateCompanies.push($(this).attr('href'));
			$(this).triggerModal('corporate', $('.portfolio-list a', '#set-2').index($(this)));
		});
	}
}
	
function teamDetail() {
	if ($('body').width() > 700) {
		$('a', '#team-list').each(function() {
			teamMembers.push($(this).attr('href'));
			$(this).triggerModal('team', $('a', '#team-list').index($(this)));
		});
	}
}

$.fn.triggerModal = function(type, itemIndex) {
	var currentItem;
	var template;
	var currentHeight;
	currentData = {};
	lateral = false;

	this.click(function() {	
		switch (type) {
			case 'team' :
				currentItem = teamMembers[itemIndex];
				totalItems = teamMembers.length;
				template = teamTemplate;
				currentWidth = 850;
				currentHeight = 640;
				break;
			case 'portfolio' :
				currentItem = portfolioCompanies[itemIndex];
				totalItems = portfolioCompanies.length;
				template = portfolioTemplate;
				currentWidth = 700;
				currentHeight = 350;
				break;
			case 'corporate' :
				currentItem = corporateCompanies[itemIndex];
				totalItems = corporateCompanies.length;
				template = portfolioTemplate;
				currentWidth = 700;
				currentHeight = 350;
				break;
		}
		
		// Create a shadowbox or just relod its content?
		if (Shadowbox.isOpen()) {
			lateral = true;
			modalHTML = $('#sb-player');
		}
		else {
			modalHTML = $(template).clone();
		}
		
		// Set up values of next/previous
		prevItem = (itemIndex - 1) >= 0 ? (itemIndex - 1) : (totalItems - 1);
		nextItem = (itemIndex + 1) < totalItems ? (itemIndex + 1) : 0;
				
		$.ajax({
	  		url: currentItem,
	  		dataType: 'text',
	 		success: function(text) {	 			 			
	  			ajaxData = $(text);	  	
	  			if (type == 'team') {						
		  			currentData[currentItem] = {
		  				'title' : ajaxData.find('h1.title').html(),
		  				'details' : ajaxData.find('div.details').html(),
		  				'img' : ajaxData.find('div.img').html()
		  			};
		  		}
		  		else if (type == 'portfolio' || type == 'corporate') {
					currentData[currentItem] = {
		  				'title' : ajaxData.find('h1.title').html(),
		  				'details' : ajaxData.find('div.details').html(),
		  				'img' : ajaxData.find('div.img').html(),
		  				'website': ajaxData.find('#view-website').attr('href'),
		  				'twitter': ajaxData.find('#view-twitter').attr('href')
		  			};
	  			}
	  			
	  			// Apply the AJAX data
				$('h2', modalHTML).html(currentData[currentItem]['title']);
				$('#modal-content', modalHTML).html(currentData[currentItem]['details']);
				$('#modal-content', modalHTML).prepend(currentData[currentItem]['img']);
				
				// Portfolio only data
				if (type == 'portfolio' || type == 'corporate') {
					if (currentData[currentItem]['website']) {
						$('#modal-content', modalHTML).append('<a target="_blank" id="view-website" href="' + currentData[currentItem]['website'] + '" title="' + currentData[currentItem]['title'] + '">View Website</a>');
					}
					if (currentData[currentItem]['twitter']) {
						$('#modal-content', modalHTML).append('<a target="_blank" id="view-twitter" href="' + currentData[currentItem]['twitter'] + '" title="' + currentData[currentItem]['title'] + '">View Twitter</a>');
					}
				}
				
				// Open the new Shadowbox or just set the new next/prev
				if (lateral == false) {		
					// Open the modal
					Shadowbox.open({
				        content: modalHTML.html(),
				        player: "html",
				        width: currentWidth,
				        height: currentHeight,
				        options: { 
	           			onFinish: function() {				
							// Next/prev buttons (need to exist before receiving trigger)
							$('a.prev').triggerModal(type, prevItem);
							$('a.next').triggerModal(type, nextItem);
	           				} 
	            		} 
				    });	
				}
				else {
					$('a.prev').unbind('click').triggerModal(type, prevItem);
					$('a.next').unbind('click').triggerModal(type, nextItem);
				}		
	  		}
		});
		
		return false;	
	});	
}

function printModal() {
	$('body').addClass('only-modal');
	window.print();
	
	return false
}

