//--[ VARS ]--//
var $contentStartHeight
var $enableClientSlideShow
var $enableServiceSlideShow
var $currentpage
var $currentsubpage
var $clickedThumb
var $slideDirection
var $nextClientNum
var $nextServiceNum
var $previousimg
var $previousimgS
var $moreswitch = false;
//--[ FUNCTIONS ]--//

var Main = {
	setup : function ()
	{
		//--set vars
		$contentStartHeight = $('#content').height()
		$nextClientNum = 9
		$nextServiceNum = 9
		$previousimg = 0
		$previousimgS = 0
		$enableClientSlideShow = false
		$enableServiceSlideShow = false
		//--add handlers
		addMouseHandlers()
		$(function(){
			$(window).bind('hashchange', function(){ //using jQuery hashchange event - v1.3 by Ben Alman (js/jquery.ba-hashchange.min.js)
				onHashChange(getCurrentHash())
			})
		});
		//--start site
		onHashChange(getCurrentHash())
	}	
}

function consolelog($str)
{
    try {
      console.log($str);
    } catch(e) {
      //do nothing
    }
}
function getCurrentHash()
{
    var str = location.hash
    str = str.replace('#/','')
    str = str.substring(0, str.length - 1)
    return str
}
function onHashChange(page){
	var subpage
	var subsubpage
	if (page.search('/') != -1) var pages = page.split('/', 3)
	if (pages){
		if (pages[0]) page = pages[0]
		if (pages[1]) subpage = pages[1]
		if (pages[2]) subsubpage = pages[2]
	}
	consolelog('change the page OLD: [' + $currentpage + '/' + $currentsubpage + ']   NEW: page[' + page + '] subpage[' + subpage + '] subsubpage[' + subsubpage + ']')
	if (page && subpage && subsubpage) {
		pageTracker._trackPageview('/' + page + '/' + subpage + '/' + subsubpage);
	}else if (page && subpage){
		pageTracker._trackPageview('/' + page + '/' + subpage);
	}else if (page){
		pageTracker._trackPageview('/' + page );
	}else{
		pageTracker._trackPageview('/home');
	}
	if (errorCheckUrl(page, subpage)) handlePageChange(page, subpage)
}
function errorCheckUrl(page, subpage)
{
	var boo = true
	var newpage = page
	var newsubpage = subpage
	//-->will check if the url has been constructed correctly 
	switch(page)
	{
		case 'film':
			newsubpage = $xmltext['dept1a']['tag']
			if (page && !subpage) boo = false
		break;
		case 'interactive':
			newsubpage = $xmltext['dept2a']['tag']
			if (subpage == 'advertising') {
				boo = false
				window.location.hash = "#/" + page + "/"
				return
			}
			if (page && !subpage) boo = false
		break;
		case 'production':
			newsubpage = $xmltext['dept3a']['tag']
			if (page && !subpage) boo = false
		break;
		case 'rushmore':
			newsubpage = $xmltext['dept4a']['tag']
			if (page && !subpage) boo = false
		break;
		case 'search':
			newsubpage = $xmltext['dept4a']['tag']
			if (page && !subpage) boo = false
		break;
		case 'about':
		case 'contact':
        case 'services':
        case 'careers':
		break;
		case 'showreel':
			if (page && subpage){
				window.location.hash = "#/" + page + "/"
				return
			}
		break;
		default:
			if (page) {
				boo = false
				window.location.hash = ''
				location.reload(true);
				return
			}
	}
	if (!boo) window.location.hash = "#/" + newpage + "/" + newsubpage + "/"
	return boo
}
function handlePageChange(page, subpage)
{	
	$('.jobholder').children('.jobdesc2').hide();
    $('.jobholder').children('.jobdesc').show();
	$('.jobholder').fadeIn(400);
	$('.readme').html($xmltext['clickme']['copy']);
	
	var lastpage = $currentpage
	var lastsubpage = $currentsubpage
	$currentpage = page
	$currentsubpage = subpage
	if (page != 'contact') HandleMaps.close()
	$("#more").fadeOut('fast');
	$('.sidebarsubnav').fadeOut('fast')
	if (page == 'about' || page == 'services' || page == 'contact' || page == 'careers' || page== 'videopage')
	{
		openHeaderPage(page, lastpage)
        $("#content").css({"margin-bottom":10, "height":545})
		
	}else if (page == 'film' || page == 'interactive' || page == 'production' || page == 'rushmore' || page == 'showreel'){
         $("#content").css({"margin-bottom":50, "height":585})
		
		var pat = /^\s*\d+\s*$/
		var openvideo = pat.test(subpage)
		//consolelog('openvideo before [' + openvideo + '] test[' + subpage + ']  pattern[' + pat +']')
		
		if (subpage == $xmltext['dept1a']['tag'] || subpage == $xmltext['dept1b']['tag'] || subpage == $xmltext['dept1c']['tag']) openvideo = false
		if (page == 'showreel') {
			openvideo = true
			 $("#content").css({"margin-bottom":0, "height":505})
		}
		
		if (openvideo && $slideDirection && $slideDirection != null){
			changePageSlide($('#videopage'), $('#videopage'), true)
		}else if(openvideo){
			 $("#content").css({"margin-bottom":0})
			if (lastpage == 'about' || lastpage == 'services' || lastpage == 'contact' || lastpage == 'careers'){
				//changePage($('#' + lastpage), $('#mainpages'))
				consolelog('lastpage:' + lastpage + '  || page:' + page)
				$('#about, #services, #contact, #careers').fadeOut(750)
			}
			animateThumbsOut($clickedThumb)
			
		}else{
			$('#videopage').fadeOut(0)
			HandleVideo.closeVideo()
			openAndHighlightMenu(page, subpage)
			HandleThumbs.setupThumbs(page, subpage)
			$('#mainpages').delay(100).fadeIn(0)
			$('#thumbs').delay(100).fadeIn(0)
			animateThumbsIn()
		}
	}else{
		HandleVideo.closeVideo()
		$('#videopage').fadeOut(0)
		HandleThumbs.setupThumbs(page, subpage)
		
		var delay  = 750
		if (page == 'search') delay = 0
		
		setTimeout(function(){
			$('#mainpages').fadeIn(0)
			$('#thumbs').fadeIn(0)
			animateThumbsIn()
		}, delay)
	}
}

function openAndHighlightMenu(page, subpage)
{
	//highlight and open the menu
	var $target = $('#' + page)
	var $targetSubNav = $target.find('.sidebarsubnav')
	$targetSubNav.fadeIn('fast')
	var $subtarget = $targetSubNav.find('#' + subpage)
	if($subtarget){
		$subtargetText = $subtarget.find('a')
		$('.sidebarsubnav a').css({backgroundColor: 'transparent'})
		$('.sidebarsubnav a').css({color: '#979AA2'})
		$subtargetText.css({color: '#00A8F7'})
	}
}

function subpageToNum(subpage)
{
	var num = 0
	
	switch(subpage){
		case '2011':
			num = 0
		break;
	}
	
	return num
}

function selectJobs(evt)
{
    var $target = $(evt.currentTarget).parent();
    
    if ( $('#jobcontainer').data('is_open') == false)
    {
        $('#jobcontainer').data('is_open', true); 
        
        $('.jobholder').fadeOut(400, function() {
        
            $target.parent('.jobholder').fadeIn(400, "linear");
            $target.parent('.jobholder').children('.jobdesc').hide();
            $target.parent('.jobholder').children('.jobdesc2').show();
            $('.readme').html($xmltext['backme']['copy'])
        });
    } else {
        $('#jobcontainer').data('is_open', false);
        
         $('.jobholder').fadeIn(400, function() {
            $target.parent('.jobholder').children('.jobdesc2').hide();
            $target.parent('.jobholder').children('.jobdesc').show();
            $('.readme').html($xmltext['clickme']['copy'])
        });
    }
}

function openHeaderPage(page, lastpage)
{
	consolelog(' ---> page: ' + page + '  ---> laspage: ' + lastpage)
	$target = $('#' + page)
    $targetText = $target.find('.headertext')

	HandleVideo.closeVideo()
	
	//if ($('.sidebarnav').css('display') != 'none') $('.sidebarsubnav').fadeOut('fast')
	
	var index = 0
	if (page == 'about') index = 1
	if (page == 'contact') index = 2
    if (page == 'careers') index = 3
	var $target = $('.headertext:eq(' + index + ')');
	$target.data('isactive', true)
	var $targetText = $target.find('a')
	
    if (page == 'services' || page == 'about' || page == 'contact' || page == 'careers' || page == 'blog')
    {
        $('.headertext a').css({color: '#ffffff'})
        $targetText.css({color: '#cccccc'})
    } else {
        $('.headertext a').css({color: '#cccccc'})
        $targetText.css({color: '#00A8F7'})
    }
	
	if (page == 'about')
	{
		$enableClientSlideShow = true
		setTimeout(function(){clientSlideShow()}, 750);
	}
	
	if (page == 'services')
	{
		//$enableServiceSlideShow = true
		//setTimeout(function(){serviceSlideShow()}, 750);
	}
    
    if (page == 'careers')
	{
		//$enableServiceSlideShow = true
		//setTimeout(function(){serviceSlideShow()}, 750);
	}
	
	if (page == 'contact') setTimeout(function() { HandleMaps.setup(0) }, 1000);
	
	if (lastpage == 'about' || lastpage == 'services' || lastpage == 'contact' || lastpage == 'careers'){
	
		if ($slideDirection && $slideDirection != null)
		{
			changePageSlide($('#' + lastpage), $('#' + page), false)
		}else{
			changePage($('#' + lastpage), $('#' + page))
		}
	}else{
		$('#headerpages').fadeIn(0)
		$('#about, #services, #contact, #careers').fadeOut(0)
		changePage($('#mainpages'), $('#' + page))
	}
}

function createwordcloud()
{
	
	var str = ''
	var strarr = $xmltext['wordcloudtext']['copy'].split(',')
	
	var isEven = function(someNumber){
		return (someNumber%2 == 0) ? true : false;
	};
	
	for ($x in strarr)
	{
		var col = '#979AA2'
		if ($x % 2 == 0) col = '#979AA2'
		str += '<font size="5" color="' + col + '">'
		str += strarr[$x]
		str += '</font>'
		
		if ($x < strarr.length - 1 ) str += '<font color="#00A8F7"> &bull; </font>'
		
	}
	
	$('#wordcloud').html(str)
}

function changePage($closeMe, $openMe)
{
	var $duration = 300
	var $pause = 300
	
	$closeMe.fadeOut($duration, function(){
		$openMe.delay($pause).fadeTo($duration, 1)
	})
}

function changePageSlide($closeMe, $openMe, $isVideo)
{
	var $duration = 750
	var $x = '-900px'
	var $y = '900px'
	
	if ($slideDirection == 'right')
	{
		var $x = '900px'
		var $y = '-900px'
	}
	
	if ($slideDirection) $slideDirection = null
	
	if ($closeMe[0] != $openMe[0]) $openMe.fadeOut(0)
	
	$closeMe.find('.slideObject').delay(100).animate({'left': $x}, $duration, function(){
		if ($isVideo) HandleVideo.setupVideo($currentpage, $currentsubpage) //change the video // department, video_id
		$closeMe.fadeOut(0)
		$closeMe.find('.slideObject').css("left", '0px')
		$openMe.find('.slideObject').css("left", $y)
		$openMe.fadeIn(0)
		$openMe.find('.slideObject').delay(300).animate({'left': '0px'}, $duration, function()
		{
			if ($isVideo) HandleVideo.playVideo()
		})
	})
}

function addMouseHandlers(){
	$('.hashLink').click(function (evt) {
		evt.preventDefault();
		if (this.name == 'null') return
		location.hash = '#/' + this.name + '/';
	});
	
	$('#contact_address_button').click(function(evt){onClickAddressBtn(evt)})
	$('#contact_address_button').data('showingLondon', true);
	$('#logoATag').click(function(evt){onClickLogo(evt)})
	$('#moretext').click(function(evt){HandleThumbs.showMore(evt)})
	$('.headertext:lt(3), .sidebarsubtext, .sidebartext').click(function(evt){onClickText(evt)});
	$('#video_closebutton').click(function(){HandleVideo.onClickClose()}).mouseenter(function(evt){HandleVideo.onOverClose(evt)}).mouseleave(function(evt){HandleVideo.onOutClose(evt)});
	$('.prevText, .nextText').click(function(evt){setSlideDirection(evt)});
	$('.readmore_button').click(function(evt){HandleVideo.clickReadMore(evt)});
	$('.headertext').mouseenter(function(evt){higlightTop(evt)}).mouseleave(function(evt){unhiglightTop(evt)});
    $('.sidebartext, .sidebarsubtext, .prevNextText, #hsocial, #aboutimg_wrapper, #socialcontacts').mouseenter(function(evt){higlightSide(evt)}).mouseleave(function(evt){unhiglightSide(evt)});
	$('#searchimg').click(function(evt){onClickSearchImg(evt)}).mouseenter(function(evt){onOverSearchImg(evt)}).mouseleave(function(evt){onOutSearchImg(evt)});
	$('#aboutimg_wrapper').click(function(evt){onClickShowreel(evt)})
    $('#jobcontainer').data('is_open', false)
    $('.readme').click(function(evt){selectJobs(evt)})
	$('.headertexticon').mouseenter(function(evt){onOverHeaderIcon(evt)}).mouseleave(function(evt){onOutHeaderIcon(evt)})
}

function onClickLogo(evt)
{
	evt.preventDefault();
	location.reload(false);
}

function setSlideDirection(evt)
{
	consolelog('setSlideDirection called ' + $currentpage)
	if ($currentpage == 'about' || $currentpage == 'services' || $currentpage == 'contact'  || $currentpage == 'careers'){
		$('.headertext:lt(3)').data('isactive', false)
		$('.headertext a').css({color: '#cccccc'})
	}
	
	var $target = $(evt.currentTarget);
	if ($target.css('float') == 'right'){
		$slideDirection = 'right'
	}else{
		$slideDirection = 'left'
	}
}

function onClickAddressBtn(evt)
{
	$target = $(evt.currentTarget);
	var $time = 250
	
	HandleMaps.close()
	
	$('#contact_address_button').fadeOut($time)
	
	if ($target.data('showingLondon')) {
        $target.data('showingLondon', false);
		
		$('#contact_address_london').fadeOut($time, function()
		{
			$('#contact_address_button').find('a').html('&lt;&lt; LONDON')
			$('#contact_address_la').delay($time).fadeIn($time)
		})
		
		HandleMaps.setup(1)
		
    }else{
		$target.data('showingLondon', true);
		$('#contact_address_la').fadeOut($time, function()
		{
			$('#contact_address_button').find('a').html('&lt;&lt; LOS ANGELES')
			$('#contact_address_london').delay($time).fadeIn($time)
		})
		HandleMaps.setup(0)
	}
	$('#contact_address_button').delay($time).fadeIn($time)
}



function clientSlideShow(){
	if ($enableClientSlideShow)
	{
		$enableClientSlideShow = false
		var $total = $('.clientThumbs').length
		//var $x = Math.floor(Math.random() * $total)
		
		var $x = $previousimg
		var $img = $($('.clientThumbs')[$x]).find('img')
		var $alt = $img.attr('alt')
		var $src = $img.attr('src')
		
		var num = 0;
		$previousimg++
		
		if ($previousimg >= 8)
		{
			$previousimg = 0;
		}
		 
		for (key in  $xmlclients) {
			num++;
		}
		
		$img.delay(2000).animate({opacity: 0}, 'slow', '', function(){
			var $str = $xmlclients[$nextClientNum]['thumb_name']
			var $alt = $xmlclients[$nextClientNum]['alt']
			$nextClientNum++
			if ($nextClientNum > num) $nextClientNum = 1
			$src = $src.replace($src, $str)
			
			$img.attr('src', $src);
			$img.attr('alt', $alt);
			$img.animate({opacity: 1}, 'slow', '', clientSlideShow)
			if ($currentpage == 'about') $enableClientSlideShow = true
		})
	}
}

function serviceSlideShow(){
	if ($enableServiceSlideShow)
	{
		$enableServiceSlideShow = false
		var $total = $('.servicesThumbs').length
		//var $x = Math.floor(Math.random() * $total)
		
		var $x = $previousimgS
		var $img = $($('.servicesThumbs')[$x]).find('img')
		var $alt = $img.attr('alt')
		var $src = $img.attr('src')
		
		var num = 0;
		$previousimgS++
		
		if ($previousimgS >= 8)
		{
			$previousimgS = 0;
		}
		 
		for (key in  $xmlservices) {
			num++;
		}
		
		$img.delay(2000).animate({opacity: 0}, 'slow', '', function(){
			
			var $str = $xmlservices[$nextServiceNum]['thumb_name']
			var $alt = $xmlservices[$nextServiceNum]['alt']
			$nextServiceNum++
			if ($nextServiceNum > num) $nextServiceNum = 1
			$src = $src.replace($src, $str)
			
			$img.attr('src', $src);
			$img.attr('alt', $alt);
			$img.animate({opacity: 1}, 'slow', '', serviceSlideShow)
			if ($currentpage == 'services') $enableServiceSlideShow = true
		})
	}
}


function changeContentHeight(num, func)
{
	var $newheight = $contentStartHeight
	if (num) $newheight = num
	
	var $time = ( $newheight - $('#content').height() ) * 4
	
	if ($('#content').height() != $newheight) {
		$('#content').animate({height: $newheight}, $time, function() {
			if (func) func()
		});
	}
}

function truncate(str, limit) {
	var bits, i;
	bits = str.split('');
	if (bits.length > limit) {
		
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		
		//bits.length = bits.length - 1; //--for the dots
		bits.push('...');
	}
	return bits.join('');
};

function onClickText(evt){

	var $target = $(evt.currentTarget);
	
	var $targetName = $target['context'].getAttribute("class");
	var $targetText = $target.find('a');
	var $targetTextName = $targetText.attr("class")

	if ($targetTextName === 'hashLink'){
		$('.sidebartext a, .sidebarsubtext a, .sidebarsubtext1 a').css({color: '#979aa2'})
        $targetText.css({color: '#00A8F7'})

		$('.headertext:lt(3)').data('isactive', false)
		
		$target.data('isactive', true);
	}
}

function higlightTop(evt){
	var $target = $(evt.currentTarget);
	var $targetText = $target.find('a')
	var $id = $target['context'].getAttribute("id")
    
	$targetText.css({color: '#979AA2'})
	
}

function unhiglightTop(evt){
	var $target = $(evt.currentTarget);
	var $targetText = $target.find('a')
	var $id = $target['context'].getAttribute("id")

	{
		$targetText.css({color: '#ffffff'})
	}
}

function higlightSide(evt){
	var $target = $(evt.currentTarget);
	var $targetText = $target.find('a')
	var $id = $target['context'].getAttribute("id")
	if ($id == 'hsocial' || $id == 'socialcontacts') $targetText = $target.find('p')
	if (!$target.data('isactive'))
	{
		$targetText.css({color: '#00A8F7'})
	}
	
	var $extimg = $target.find('#sidebarsubimg')
	if ($extimg) $extimg.css('background-position', 'top')
	
	var $aboutimge = $target.find('#aboutimg')
	if ($aboutimge) $aboutimge.css('background-position', 'top')
}

function unhiglightSide(evt){
	var $target = $(evt.currentTarget);
	var $targetText = $target.find('a')
	var $id = $target['context'].getAttribute("id")
	if ($id == 'hsocial' || $id == 'socialcontacts') $targetText = $target.find('p')
	if (!$target.data('isactive'))
	{
		$targetText.css({color: '#979AA2'})
	}
	var $extimg = $target.find('#sidebarsubimg')
	if ($extimg) $extimg.css('background-position', 'bottom')
	
	var $aboutimge = $target.find('#aboutimg')
	if ($aboutimge) $aboutimge.css('background-position', 'bottom')
}

function onOverHeaderIcon(evt)
{
	var $target = $('.headertext:eq(4)')
	var $targetText = $target.find('p')
	$targetText.css({color: '#979AA2'})
	$target = $(evt.currentTarget)
}
function onOutHeaderIcon(evt)
{
	var $target = $('.headertext:eq(4)')
	var $targetText = $target.find('p')
	$targetText.css({color: '#fff'})
	$target = $(evt.currentTarget)
}

function onClickSideNav(evt)
{
	var $target = $(evt.currentTarget);
	var $targetSubNav = $target.find('.sidebarsubnav')
	if ($targetSubNav.css('display') == 'none')
	{
		$('.sidebarsubnav').fadeOut('fast')
		$targetSubNav.fadeIn('fast')
	}
}


function animateThumbsIn(){
	
	var $allThumb = $('.thumb');
	
	//$allThumb.css("filter", "alpha(opacity=40)")
	
	//$allThumb.animate({opacity: 0}, 0)
	$allThumb.fadeOut(0)
	var $delay = 100
	
	//alert('  thumbs == ' + $allThumb.css('display'))
	
	for (i=0; i < $allThumb.length; i++)
	{
		$victim = $($allThumb[i]);
		//$victim.delay( 500 + ($delay * i)).animate({opacity: 1});
		$victim.delay( 500 + ($delay * i)).fadeIn(250, function(){
			//setTimeout(function(){alert('  victim == ' + $victim.css('display'))}, 500)
		})
		
	}
}

function animateThumbsOut(activeThumb)
{
	var $allThumb = $('.thumb');
	if ($clickedThumb) $clickedThumb = null
	
	if (activeThumb)
	{
		var $targetId
		var $opacity = 0
		var $numOfColumns = 4
		var $spacer = 10
		var $itemWidth = 175
		var $itemHeight = 130
		var $delay = 0
		
		for (i=0; i < $allThumb.length; i++)
		{
			if (activeThumb && $allThumb[i] == activeThumb[0]) $targetId = i
		}
		
		for (i=0; i < $allThumb.length; i++)
		{
			if (i != $targetId){
			
				$victim = $($allThumb[i]);
				
				if (!$targetId && i == 16)
				{
					$victim.delay($delay * i).animate({opacity: $opacity}, $delay, '', function()
					{
						onAnimateThumbsOut()
					})
					break
				}else{
					$victim.delay($delay * i).animate({opacity: $opacity}, $delay)
				}
			}else {
				var  col = ($targetId % $numOfColumns) * ($itemWidth + $spacer);
				var  row = Math.floor($targetId / $numOfColumns) * ($itemHeight + $spacer);
				var $animateTime = (col + row) * .5
				$(activeThumb[0]).delay($delay * i).animate({opacity: $opacity}, $delay, '', onAnimateThumbsOut)
				break
			}
		}
	}else{
		onAnimateThumbsOut()
		//HandleVideo.showVideoPlayer()
	}
}

function onAnimateThumbsOut()
{
	var $target = $(this)
	$('#thumbs').fadeOut(500, function() {resetThumbPos($target); HandleVideo.showVideoPlayer(); consolelog(' thumbs = ' + $('#thumbs').css('block'))});
}
function resetThumbPos($target){
	$target.css('left', '0')
	$target.css('top', '0')
}

//---- VIDEO SEARCHING ----//

function clickSearch(evt)
{
	evt.focus();
	evt.select();
}

function submitSearch()
{
	var term = document.forms["searchform"]["searchinput"].value
	document.forms["searchform"]["searchinput"].value = "SEARCH"
	window.location.hash = "#/search/" + term + "/"
}

function validateSearchForm()
{
	var boo = true
	var str = document.forms["searchform"]["searchinput"].value
	if (str.length < 3 || str == 'SEARCH') {
		$('#searchwrapper').css('backgroundColor','red')
		$('#searchwrapper').animate({'width': '175px'}, 500, function(){
			$('#searchwrapper').css('backgroundColor','transparent') //cant seem to delay css funciton or animate backgroundColor (so i hacked it)!
		})
		boo = false
	}
	return boo
}

function onOverSearchImg(evt)
{
	$('#searchimg').css('background-position','top')
}

function onOutSearchImg(evt)
{
	$('#searchimg').css('background-position','bottom')
}

function onClickSearchImg(evt)
{
	if(validateSearchForm()) submitSearch()
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function onClickShowreel()
{
	window.location.hash = "#/showreel/"
	
}
