

// ###########################################################################
// ##### GLOBAL VARIABLES
// ###########################################################################

var _contentArray = new Array(["home", "home-section"],
							  ["print_branding", "print-brand-section"],
							  ["digital", "digital-section"],
							  ["about", "about-section"],
							  ["contact", "contact-section"],
							  ["pageNotFound", "noPage-section"]);
var _currentLocation;
var _prevLocation;
var _mobileContactOpen = false;

// ###########################################################################
// ##### INIT FUNCTIONS
// ########################################################################### 



function initDisplay()
{
	for(var i = 0; i<_contentArray.length; i++)
	{
		var contentDiv = _contentArray[i][1];
		var currentDiv = document.getElementById(contentDiv);
		$(currentDiv).css( { "left": 960 + "px"} );
		$(currentDiv).hide();
	}
		imageLoad();
}

function imageLoad() {

	$('.slider').hide();
	$('.flashImage').hide();
	
	$('.slider').waitForImages(function() {
		$(this).show();
		var loader = $(this).parent().find('.sliderLoader');
		$(loader).hide();
	});
	
	$('.flashImage').waitForImages(function() {
		$(this).show();
		var loader = $(this).parent().find('.sliderLoader');
		$(loader).hide();
	});

}

function initPage()
{
	var currentHash = window.location.hash;
	var newHash;
	var location;
	var projectHash;
	var pageFound = false;
	
	if(window.location.hash.length)
	{
		var split = window.location.hash.split('/');
		location = split[split.length - 1];
		
		_currentLocation = location;
		_prevLocation = location;
		
		var wrapper = document.getElementById("sectionwrapper");
		var currentDiv = location;
		for(var i = 0; i< _contentArray.length; i++)
		{
			var value = _contentArray[i][0];
			if(currentDiv == value) 
			{
				currentDiv = _contentArray[i][1];
				pageFound = true;
				break;
			}
		}
		
		if(pageFound == false)
		{
			currentDiv = 'noPage-section'; 
			_currentLocation = "noPage-section";
			_prevLocation = "pageNotFound";
			location = "pageNotFound";
		}
		
		var newDiv = document.getElementById(currentDiv);
		var currentHeight = $(newDiv).height();
		$(wrapper).css( { "height": currentHeight + "px"} );
		$(newDiv).css( { "left": 0 + "px"} );
		$(newDiv).show();
		
		displayContent(location);
		updateNavigation(location);
		updateLocation(location);
	}
	
	else
	{
		_currentLocation = "home";
		_prevLocation = "home";
		var homeDiv = document.getElementById("home-section");
		$(homeDiv).css( { "left": 0 + "px"} );
	
		//update wrapper size
		var wrapper = document.getElementById("sectionwrapper");
		var currentHeight = $(homeDiv).height();
		$(wrapper).css( { "height": currentHeight + "px"} );
		$(homeDiv).show();
	}
	
	featureAnimate();
}

// ###########################################################################
// ##### NAVIGATE
// ###########################################################################

function navigate()
{
	$("#home").addClass('active');
	$(".nav li").mouseover(function(e)
	{
		$(this).css('cursor', 'pointer');
	});
	
	$(".backToTop").mouseover(function(e)
	{
		$(this).css('cursor', 'pointer');
	});
	
	$(".mastheadLink").mouseover(function(e)
	{
		$(this).css('cursor', 'pointer');
	});
	
	$(".featureBox").mouseover(function(e)
	{
		$(this).css('cursor', 'pointer');
	});
	enableNav();
}

function enableNav()
{	
	$("#headerlogo").bind('click', (function(e)
	{
		if(_currentLocation != "home")
		{
			disableNav();
			e.preventDefault();
			displayContent("home");
			updateLocation("home");
			$('.nav li').removeClass('active');
			$('.nav li#home').addClass('active');
		}
	})
	);
	
	$('.nav li').bind('click', (function(e)
	{	
/* 		$(this).fadeIn(300); */
		if(this.id != _currentLocation)
		{
			disableNav();
			e.preventDefault();
			displayContent(this.id);
			updateLocation(this.id);
			$('.nav li').removeClass('active');
			$(this).addClass('active');
		}
	})
	);
	
	$('.backToTop').bind('click', (function(e)
	{
		var offset = ($(document).scrollTop() / 100) * 20;
		$(document).scrollTo( '0px', offset, { easing: 'easeInSine' });
	})
	);
	
		
	$('.featureBox').bind('click', (function(e)
	{
			var locationTemp;
			var navTemp;
			if(this.id == "print") locationTemp = "print_branding";
			if(this.id == "digital") locationTemp = "digital";
			if(this.id == "hello") locationTemp = "contact";
			
			disableNav();
			e.preventDefault();
			displayContent(locationTemp);
			updateLocation(locationTemp);
			$('.nav li').removeClass('active');
			
			if(this.id == "print") $('.nav li#print_branding').addClass('active');
			if(this.id == "digital") $('.nav li#digital').addClass('active');
			if(this.id == "hello") $('.nav li#contact').addClass('active');
	})
	);
	
	$('.mastheadLink').bind('click', (function(e)
	{
		disableNav();
		e.preventDefault();
		displayContent("about");
		updateLocation("about");
		$('.nav li').removeClass('active');
		$('.nav li#about').addClass('active');
	})
	);
}

function disableNav()
{
	$("#headerlogo").unbind('click');
	$(".nav li").unbind('click');
	$(".footerImage").unbind('click');
	$('.featureBox').unbind('click');
	$('.mastheadLink').unbind('click');
}

function updateNavigation(currentItem)
{
	$('.nav li').removeClass('active');
	var item = "#" + currentItem;
	$(item).addClass('active');
}

function updateLocation(location)
{
	_currentLocation = location;
	if(_currentLocation != "home") window.location.hash = "/" + _currentLocation;
	else { window.location.hash = "#" + "/";}
	return false;		
}

function amendLocation()
{
	if(window.location.hash.length == 2) window.location.hash = ""; 
}

function mobileNavigate()
{
	$("#mobileContactBtn").bind('click', function(e)
	{	
		if(!_mobileContactOpen)
		{
			$("#mobileContact").show();
			//var str = "contact (close)";
   			 //$("#mobileContactBtn a").html(str);
			$("#mobileContactBtn").addClass('active');
			_mobileContactOpen = true;
		}
		
		else
		{ 
			$("#mobileContact").hide();
			$("#mobileContactBtn").removeClass('active');
			_mobileContactOpen = false;
		}
	});
}
 

// ###########################################################################
// ##### CONTENT - DISPLAY & ANIMATE
// ########################################################################### 

function displayContent(content)
{	
	var prevContent = _prevLocation;
	var prevIndex;
	var currentIndex;
	var currentDiv;
	var prevDiv;

	//get content index values
	for(var i = 0; i< _contentArray.length; i++)
	{
		var value = _contentArray[i][0];
		if(prevContent == value) 
		{
			prevContent = _contentArray[i][1];
			prevIndex = i;
			break;
		}
	}
	
	for(var i = 0; i< _contentArray.length; i++)
	{
		var value = _contentArray[i][0];
		if(content == value) 
		{
			content = _contentArray[i][1];
			currentIndex = i;
			break;
		}
	}

	currentDiv = document.getElementById(content);
	prevDiv = document.getElementById(prevContent);

	//adjust wrapper size then animate
	var prevId = $(prevDiv).attr('id');
	if(prevId == "home-section" || prevId == "about-section" || prevId == "about-section" || prevId == "noPage-section")
	{
		updateWrapper(currentDiv);
		animateContent(prevDiv, prevIndex, currentDiv, currentIndex);
	}
	//animate
	else {animateContent(prevDiv, prevIndex, currentDiv, currentIndex);}
	//fade on scroll
	//enableInView(currentDiv, 600)
}

// ###########################################################################
// ##### INIT FUNCTIONS
// ########################################################################### 

function createModal(ref)
{
	stopWheel(); //prevent mouse from scrolling back page
	
	var currentScroll = $(document).scrollTop();
	var currentRef = ref;
	var src;
	var modalWidth;
	var modalHeight;
	
	//modal content selection
	if(currentRef == 1)
	{
		src = "http://www.thewhitesite.co.uk/media/flash/westpac_essentials/westpac_essentials.html";
		modalWidth = 700;
		modalHeight = 450;
	}
	
	else if(currentRef == 2)
	{
		src = "http://www.thewhitesite.co.uk/media/flash/audiA4Banners/audi_A4Banners.html"
		modalWidth = 700;
		modalHeight = 700;
	} 
	
	else if(currentRef == 3)
	{
		src = "http://www.thewhitesite.co.uk/media/flash/westpac_moneyMatters/westpac_moneyMatters.html"
		modalWidth = 420;
		modalHeight = 700;
	} 
	
	else if(currentRef == 4)
	{
		src = "http://www.thewhitesite.co.uk/media/flash/telecom_wirelessModem/telecom_wirelessModem.html"
		modalWidth = 700;
		modalHeight = 500;
	}
	
	else if(currentRef == 5)
	{
		src = "http://www.thewhitesite.co.uk/media/flash/telecom_mobileTV/telecom_mobileTV.html"
		modalWidth = 650;
		modalHeight = 500;
	}

	$.modal('<iframe src="' + src + '" height="' + modalHeight +'" width="'+ modalWidth + '" style="border:0">', 
	{
		closeHTML:"",
		containerCss: 
		{
			backgroundColor:"#fff",
			height:"modalHeight",
			padding:0,
			width: "modalWidth",
			borderStyle: "solid",
			borderWidth: 10,
			borderColor: "#c6c6c6"
		},
		
		overlayClose:true,
		position: [100, 0],
		modal:true,
		opacity:97,
		overlayCss: {backgroundColor:"#f9f9f9"},
		onOpen: function (dialog) 
		{
			dialog.overlay.fadeIn(400, function () 
			{
				dialog.container.fadeIn(800),
				dialog.data.fadeIn(800);
			});
		},
		onClose: function (dialog)
		{
			$(document).scrollTo( currentScroll, 0, { easing: 'easeInSine' });
			dialog.overlay.fadeOut(400),
			dialog.container.fadeOut(400),
			dialog.data.fadeOut(400, function() 
			{
				$.modal.close(),
				startWheel();
			});
		}
	});
	
	return false;
}

// ########################################################################### 
// ##### MOUSEWHEEL CONTROLS
//########################################################################### 


function stopWheel()
{ 
	//$("body").css({ overflow: 'hidden' })
	document.onmousewheel = function(){ onWheel(); } /* IE7, IE8 */
	if(document.addEventListener)
	{ 
		/* Chrome, Safari, Firefox */
	    document.addEventListener('DOMMouseScroll', onWheel, false);
	}
	
	return false;
}

function startWheel()
{
	//$("body").css({ overflow: 'inherit' })
	document.onmousewheel = null;  /* IE7, IE8 */
	if(document.addEventListener)
	{ 
		/* Chrome, Safari, Firefox */
	    document.removeEventListener('DOMMouseScroll', onWheel, false);
	}
}
 
function onWheel(e)
{
    if(!e)
    { e = window.event; } /* IE7, IE8, Chrome, Safari */
    if(e.preventDefault) 
    { e.preventDefault(); } /* Chrome, Safari, Firefox */
    e.returnValue = false; /* IE7, IE8 */
}


// ###########################################################################
// ##### FADE ON SCROLL
//###########################################################################
function enableInView(currentDiv, timimg)
{
	var divInView = currentDiv;
	
	var allDivs = new Array();
	allDivs = currentDiv.getElementsByTagName("*");
	
	for (i=0; i<allDivs.length; i++) 
	{
		if (allDivs[i].className == "project_light" || allDivs[i].className == "project_light_large" || allDivs[i].className == "project_dark" || allDivs[i].className == "project_dark_large")
		{
			var currentSlider = allDivs[i];
			$(currentSlider).animate({opacity: 0}, 0);
			
			$(currentSlider).bind('inview', function(event, visible) {
		      if (visible) 
		      {
		        $(this).stop().animate({ opacity: 1 }, timimg);
		      } 
		      else 
		      {
		        $(this).stop().animate({ opacity: 0 }, timimg);
		      }
		    });
		}
	}
}


function updateWrapper(currentContent) 
{
	//update section wrapper height
	var wrapper = document.getElementById("sectionwrapper");
	var currentHeight = $(currentContent).height();
	$(wrapper).css( { "height": currentHeight + "px"} );
}

// ###########################################################################
//	##### ANIMATE CONTENT
//###########################################################################
function animateContent(prevContent, prevIndex, currentContent, currentIndex)
{
	 var finalCurrPos;
	 var finalPrevPos;
	 var animValue = 450;
	 var easing = 'easeInSine';
	 $(currentContent).show();
 
	 if($(document).scrollTop() < 100) initAnimation(0);
	 
	 else 
	 { 
	 	var offset = ($(document).scrollTop() / 100) * 20;
	 	$(document).scrollTo( '0px', offset, { easing: easing, onAfter:function(){initAnimation(90)} }); 
	 	//$(prevContent).animate({opacity:1}, offset);
	 }
	 
	
	function initAnimation(delay)
	{
		if(prevIndex < currentIndex) 
		{
			$(currentContent).css( { "left": 960 + "px"} );
			finalPrevPos = $(prevContent).position().left - 960;
			finalCurrPos = $(currentContent).position().left - 960;
			
			
			$(prevContent).delay(delay, function()
			{
				$(prevContent).animate(
				{ left: finalPrevPos, opacity: 0}, 
					{
						duration: animValue, 
						easing: easing,
						complete: function() 
						{
						    $(this).css( { "left": 960 + "px"} );
						    $(this).hide();
						    _prevLocation = _currentLocation;
						    updateWrapper(currentContent);
						    enableNav();
						    amendLocation();
						}
					});
				  
				  $(currentContent).animate(
				  { left: finalCurrPos, opacity: 1},
					  {		
					  		duration:animValue,
					    	easing: easing
					});
			});
		}
		
		if(prevIndex > currentIndex) 
		{
			$(currentContent).css( { "left": -960 + "px"} );
			finalPrevPos = $(prevContent).position().left + 960;
			finalCurrPos = $(currentContent).position().left + 960;
			
			$(prevContent).delay(delay, function()
			{
				$(prevContent).animate(
				{ left: finalPrevPos,opacity: 0}, 
					{ 
						duration:animValue, 
						easing: easing, 
						complete: function() 
						{
						 	 $(this).hide();
						    _prevLocation = _currentLocation;
						    updateWrapper(currentContent);
						    enableNav();
						    amendLocation();
						}
				});
				  
				  $(currentContent).animate(
				  { left: finalCurrPos, opacity: 1},
				    {
				    	duration:animValue,
				    	easing: easing
				    });
		    });
		}
	}
}

// ########################################################################### 
//	##### SLIDER
//###########################################################################

function slider()
{	
	//init slider active images
	var allDivs = new Array();
	allDivs = document.getElementsByTagName("*");
	
	for (i=0; i<allDivs.length; i++) 
	{
		if (allDivs[i].className == "slider") 
		{
			var currentDiv = allDivs[i];
			$(currentDiv).find('img').eq(0).addClass('active');
			
			//update image text
			var tempStr = $(currentDiv).attr('id').split('slider');
			var currentControl = "controls" + tempStr[tempStr.length -1]; 
			var currentTotal = $(currentDiv).find('img').size();
			document.getElementById(currentControl).innerHTML = "1 of " + currentTotal;
		}
	}

	var imagewidth = $('.sliderContainer_right').width();                  
    var totalimages = $('.slider img').size();
    	   
    var sliderwidth = imagewidth * totalimages;                   
    $('.slider').css({'width': sliderwidth});  
                    
	var currentSlider;
	var nextImage;
    
    $('.next').click(function()
    {
        nextImage = "slider" + $(this).attr('id');
        currentSlider = document.getElementById(nextImage);        
        updateNext();
        return false;
    }); 

    $('.previous').click(function()
    {                              
        nextImage = "slider" + $(this).attr('id');
 		currentSlider = document.getElementById(nextImage);
        updatePrev();
        return false;
    });
    
    function updateNext()
    {
		var $active;
		var currentImageNumber;
		var tempStr = $(currentSlider).attr('id').split('slider');
		var currentControl = "controls" + tempStr[tempStr.length -1];
		var currentTotal = $(currentSlider).find('img').size();
		
		$active =  $(currentSlider).find('img.active').parent().next().children();

        if ($active.length==0) 
        {
        	$active =  $(currentSlider).find('img').eq(0);
        	currentImageNumber = 0;
      		document.getElementById(currentControl).innerHTML = currentImageNumber + " of " + currentTotal;
        }

        $(currentSlider).find('img.active').removeClass('active');        
        $active.addClass('active');  

        var count = $active.attr('alt') -1; 
        var sliderposition = count * imagewidth;  
        $(currentSlider).animate({'left': -sliderposition}, 500); 
        
        //update image text
        var split = document.getElementById(currentControl).innerHTML.split(' of');
        currentImageNumber = Number(split[0]);
        currentImageNumber += 1;
      	document.getElementById(currentControl).innerHTML = currentImageNumber + " of " + currentTotal;     
    }
    
    function updatePrev()
    {
     	var $active;
     	var currentImageNumber;
		var tempStr = $(currentSlider).attr('id').split('slider');
		var currentControl = "controls" + tempStr[tempStr.length -1];
		var currentTotal = $(currentSlider).find('img').size();
		
        $active =  $(currentSlider).find('img.active').parent().prev().children(); 
                         
        if ($active.length==0) 
        {
        	$active =  $(currentSlider).find('img').last();
        	currentImageNumber = currentTotal + 1;
      		document.getElementById(currentControl).innerHTML = currentImageNumber + " of " + currentTotal;
        }
        
        $(currentSlider).find('img.active').removeClass('active');                   
	    $active.addClass('active');                               
	
	    var count = $active.attr('alt') -1;
	    var sliderposition = count * imagewidth;                  
	    $(currentSlider).animate({'left': -sliderposition}, 500); 
	    
	    //update image text
        var split = document.getElementById(currentControl).innerHTML.split(' of');
        currentImageNumber = Number(split[0]);
        currentImageNumber -= 1;
      	document.getElementById(currentControl).innerHTML = currentImageNumber + " of " + currentTotal;   
    }
}

//########################################################################## 
//	##### HOME IMAGE ANIM
//########################################################################### 

var offset = 583; 


function featureAnimate() 
{ 
	var strip = document.getElementById("homeImage"); 
	offset -= 583; 
	if(offset <= - 2915) 
	{ 
		strip.style.backgroundPosition = '0px 0px'; 
		offset = 0; 
	} 
	else 
	{ 
		strip.style.backgroundPosition = offset + 'px 0px';
	} 
	window.setTimeout(featureAnimate, 3000); 
}

//########################################################################### 
//	##### UTILITIES
//########################################################################### 

$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
}

//########################################################################### 
//	##### INIT
//###########################################################################

$(document).ready(function() 
{
	initDisplay();
	initFunctional();
	initPage();
	slider();
});

$(document).load(function () 
{
    var loader = $('.slider').parent().find('.sliderLoader');
	$(loader).hide();
	var flashLoader = $('.flashImage').parent().find('.sliderLoader');
	$(flashLoader).hide();
    $('.slider').show();
	$('.flashImage').show();
});

function initFunctional()
{
	navigate();
	mobileNavigate();
}


