
// Enhanced stylesheet for users with js
document.write('<link rel=\"stylesheet\" href=\"/css/tatemovieproject-enhanced.css\" type=\"text/css\" media=\"screen\" />');


/* Cufon */
Cufon.replace('.pageTitle, .pageHeading, .smallHeading, .replace, .button, .trophies .wrp span, #newAward div.wrp span, .timeline li a, .progress .item',{hover: true});

function tateResize( size )
{
  var flash = document.getElementById('landingFlashTargetObj'),
  flash_container = document.getElementById('landingFlashPlaceHolder');
  flash.style.height = size + 'px';
  flash_container.style.height = size + 'px';
}

/**
 * DOM Load
 */
$(document).ready(function() {

	muteButton();
	subsButton();
	galleryList();
	modalLinks();
	clearField();
	doLocations();
	requestsList();
	inPageLinksScrollTo();

	// Sequencially turn on trophy lights
	var t = 0;
	$(".trophies dl dt b").each(function(i){
		var obj = $(this);
		t+=300;
		if($.browser.msie) {
			setTimeout(function(){ obj.show() },t);
		} else {
			setTimeout(function(){ obj.fadeIn() },t);
		}
	})

	// Buddies list tooltip
	$(".largeBuddiesList li li").each(function(){
		var t = $("b",this).html().split(":")[0];
		$(this).attr("title",t);
	})

	if($.browser.msie && $.browser.version<=6) {
		DD_belatedPNG.fix('img');
	}

	$(".cssForms").cssForms(); // CSS Stylable forms

	clickable();

	$('input:password').dPassword({
				duration: 2000,
				prefix: 'my_'
	});

	$('select.jsOptionMenu').change(function() {
		$(this).closest('form').submit();
	});

  timelineTooltips();
  trophyTooltips();
  buddyTooltips();
  
});


var muteState = ($.cookie('flashMuteState') == 'true'); // Global, for swfobject access
function muteButton() {
	$('#muteLink').html('<a href="#" class="rightLink mute' + (muteState ? ' true' : '') + '">Mute</a>');
	$('#muteLink a').click(function(e) {

		muteState = (!muteState);

		$.cookie('flashMuteState', (muteState ? 'true' : 'false'), { path: '/' });

		if (muteState) {
			$(this).addClass('true');
		} else {
			$(this).removeClass('true');
		}
		Cufon.replace('#muteLink a');

		for (k in swfRegistry) {
			var object = document.getElementById(swfRegistry[k]);
			if (object && typeof object.mute_state == 'function') {
				object.mute_state(muteState);
				if (console.log) {
					console.log('Mute state: ' + swfRegistry[k] + ' = ' + (muteState ? 'on' : 'off'));
				}
			}
		}

		return false;

	});
}

var subsState = ($.cookie('flashSubsState') == 'true'); // Global, for swfobject access
function subsButton() {
	$('#subsLink').html('<a href="#" class="rightLink subs' + (subsState ? ' true' : '') + '">Subtitles</a>');
	$('#subsLink a').click(function(e) {

		subsState = (!subsState);

		$.cookie('flashSubsState', (subsState ? 'true' : 'false'), { path: '/' });

		if (subsState) {
			$(this).addClass('true');
		} else {
			$(this).removeClass('true');
		}
		Cufon.replace('#subsLink a');

		for (k in swfRegistry) {
			var object = document.getElementById(swfRegistry[k]);
			if (object && typeof object.subtitle_state == 'function') {
				object.subtitle_state(subsState);
				if (console && console.log) {
					console.log('Subs state: ' + swfRegistry[k] + ' = ' + (subsState ? 'on' : 'off'));
				}
			}
		}

		return false;

	});
}

var swfRegistry = [];
function swfobjectreg(id) {
	swfRegistry[swfRegistry.length] = id;
}

/* tooltips for timeline */

function timelineTooltips() {
  $('.timeline li').simpletip({
    content: '<div class="wrp"></div>',
    position: 'top',
    offset: [-8, 0],
    baseClass: 'timeline-tooltip',
    onBeforeShow: function(){
      this.getTooltip().insertAfter('footer');/* needs to be a child of body for positioning to work */
      this.getTooltip().children('.wrp').append(this.getParent().find('.tooltipContent').css('display', 'block'));
    }
  }).children('a').click(function(evt){evt.stopPropagation();evt.preventDefault();});
}

/* tooltips for trophies on a desk view */

function trophyTooltips() {
  $('#deskTrophies a').simpletip({
    content: '<div class="wrp"></div>',
    position: 'top',
    offset: [0, 0],
    baseClass: 'trophy-tooltip',
    onBeforeShow: function(){
      this.getTooltip().insertAfter('footer');/* needs to be a child of body for positioning to work */
      this.getTooltip().children('.wrp').append(this.getParent().parent().find('.tooltipContent').css('display', 'block'));
    }
  });
}

/* tooltips for buddies on a desk view */

function buddyTooltips() {
  $('.buddiesList a').simpletip({
    content: '<div class="wrp"></div>',
    position: 'top',
    offset: [0, 0],
    baseClass: 'trophy-tooltip',
    onBeforeShow: function(){
      this.getTooltip().insertAfter('footer');/* needs to be a child of body for positioning to work */
      this.getTooltip().children('.wrp').append(this.getParent().parent().find('.tooltipContent').css('display', 'block'));
    }
  });
}
/* Clickable blocks */
function clickable() {
	$(".clickable:has(a):not(.disabled)").live("click",function() {
		var link = $("a",this).eq(0).attr("href");
		window.location = link;
	}).hover(function(){
		if(!$(this).hasClass("disabled")) {
			$(this).addClass("hover").css({"cursor":"pointer"});
		}
	},function(){
		$(this).removeClass("hover").css({"cursor":"default"});
	})
}

/* galleryList */
function galleryList() {
	$(".galleryList li .blockLink").hover(function(){$(this).parent().addClass("hover")},function(){$(this).parent().removeClass("hover")})
}

/* requestsList */

function requestsList() {
  $('#requestsList > li').each(function(){
    if($(this).find('.requestDesc').height() <= 20)/*add http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/ for px to em conversion*/
    {
      $(this).find('.moreLink').remove();
      return;
    }
    var closedHeight = $(this).find('.requestDesc').css('line-height');
    $(this).find('.requestDesc').data('original_height', $(this).find('.requestDesc').height() + 'px').css({'height': closedHeight}).next('.moreLink').click(function(evt){
      evt.stopPropagation();
      evt.preventDefault();
      if($(this).closest('li').hasClass('open'))
      {
        $(this).prev().animate({'height': closedHeight});
        $(this).children('span').text('Read more');
      }
      else
      {
        $(this).prev().animate({'height': $(this).prev().data('original_height')});
        $(this).children('span').text('Hide this');
      }
      $(this).closest('li').toggleClass('open');
    });
  });
  if(document.location.toString().match('#request-'))
  {
    $('#'+document.location.toString().split('#')[1]).parent().find('.moreLink').click();
  }
}
/**
 * General "init" function for progressively enhancing the page on DOM load
 */

function doLocations(){
	$('.locationWrap').each(function(){
		var each = this;
		$(this).find('.locationToggle, .dateRange').click(function(evt){
		  evt.stopPropagation();
		  evt.preventDefault();
			$(each).toggleClass('locationActive');
			return false;
		});
	}).removeClass('locationActive');
}

/**
* @desc run through locations and check the state
* of previous item for conditional border display
*/
function updateStates(){
	var prevActive = false;

	$('.locationWrap').each(function(){

		// see if previous item is active
		if(prevActive){
			$(this).addClass('locationPrevActive');
		} else {
			$(this).removeClass('locationPrevActive');
		}
		if ($(this).hasClass('locationActive')){
			prevActive = true;
		} else {
			prevActive = false;
		}

		if($(this).next().hasClass('locationActive')){
			$(this).addClass('locationNextActive');
		} else {
			$(this).removeClass('locationNextActive');
		}


	});
}

/* update login badge */

function loginBadgeUpdate() {

	$.ajax({
		type: 'GET',
		url: '/user/badge/?client=js',
		success: function(msg) {
			$('#sessionBadge').replaceWith(msg);
			Cufon.replace('#sessionBadge .replace');
			console.log(msg);
		},
		error: function(request, textStatus, errorThrown) {
			// Oh well, not a biggie
		}
	});

}

/**
 * animate page to a #elementid
 */
function inPageLinksScrollTo() {
	$(".scrollTo").click(function(){
		var href 	= $(this).attr("href");
		var	target	= $(href);
		if(target.size()>0) {
			var offset 	= target.offset()
			$('html,body').animate({scrollTop:offset.top},1000)
			return false;
		} else {
			return true;
		}
	})
}

// Load alert
function loadAlertUrl(alertUrl) {
	$.ajax({
		type: "GET",
		url: alertUrl,
		success: function(msg){
			$.modal(msg);
		},
		error: function(request, textStatus, errorThrown) {
			window.location = "/error/oops";
		}
	});
}

// Remove gallery item
function modalLinks() {
	$("a.modal").click(function() {
		$(this).closest('.modal_remove_on').removeClass('on');
		$.ajax({
			type: "GET",
			url: $(this).attr("href") + "?client=js",
			success: function(msg){
				$.modal(msg);
			},
			error: function(request, textStatus, errorThrown) {
				window.location = "/error/oops";
			}
		});
		return false;
	});
}

// "clear" x in textfield with error
function clearField(){
	$(".paperForm .fieldError").each(function(){
		// add a div into the DOM as a child of the fieldError
		var clearButton = $('<div></div>'),
		    theInput = $(this).find(':text, :password');
		if(theInput.length === 0) {return;}
		$(this).append(clearButton);
		clearButton.addClass('clearX');
		clearButton.css({
		  'top': Math.round(theInput.position().top + 15) + 'px',
		  'left':Math.round(theInput.position().left + theInput.outerWidth() - 30) + 'px'
		});
	});
}

function enterRoom(room) {

	var parentLevel = null;
	if (room == 'animation') parentLevel = 'animatorTrainee';

	if (parentLevel) {

		$.ajax({
			url: '/desk/level_next/?client=js&parent=' + escape(parentLevel),
			dataType: 'json',
			success: function(data) {
				if (data.name) {
					alert('Next Level: ' + data.name);
				}
				console.log(data);
			}
		});

	}

}

//enterRoom('animation');

function updateBreadCrumb(path, prefix) {

  /*************************
  * prefix is '#/' by default
  */
  if(!prefix) {
    prefix = '#/';
  }

	//--------------------------------------------------
	// Update links

		//--------------------------------------------------
		// Remove current links

			$('#breadcrumbLinks').empty();

		//--------------------------------------------------
		// Add home link

			var link = document.createElement('a');
			link.href = '';
			link.appendChild(document.createTextNode('Home'));

			$('#breadcrumbLinks').append(link);

		//--------------------------------------------------
		// Add sub links

			var len = path.length;
			var currentPage = null;

			for (k in path) {

				$('#breadcrumbLinks').append(' > ');

				if (k < (len - 1)) {

					var link = document.createElement('a');
					link.href = prefix + path[k].page;
					link.appendChild(document.createTextNode(path[k].name));

					$('#breadcrumbLinks').append(link);

				} else {

					$('#breadcrumbLinks').append($('<em />', {text: path[k].name}));

					currentPage = path[k].page;

				}

			}

		//--------------------------------------------------
		// Cufon

			if (Cufon) {
				Cufon.replace('#breadcrumbLinks');
			}

	//--------------------------------------------------
	// Update help link

	  setHelp(currentPage);

	//--------------------------------------------------
	// Hide footer

		if (currentPage == "home") {
			$('#subContent').show();
		} else {
			$('#subContent').hide();
		}

}


function openHelp(slug){
    $.ajax({
		type: "GET",
		url: '/help_pages/view/' + slug + "?client=js",
		success: function(msg){
			$.modal(msg);
		},
		error: function(request, textStatus, errorThrown) {
			window.location = "/error/oops";
		}
	});
}

// sets the html of the help link
function setHelp(slug){
    $('#helpLink').html('<a href="/help_pages/view/' + slug + '" class="rightLink help modal">Help</a>');
     modalLinks();
     Cufon.replace('.help');
}

// resets the help link to default (currently no help link)
function resetHelp(){
    $('#helpLink').html('');
}

// this is a copy of the function inside the modal plugin
function closeModal() {
    $("#jQueryModalWindow").fadeOut(500,function(){
     $("#jQueryModalOverlay").fadeOut();
    });
}

// insert string into textarea
function attachItem(str){
    comment_text = $('#CommentBox').val();
    if(comment_text != ''){
        comment_text = comment_text + "\n\n";
    }
    comment_text = comment_text + "[ENTRY '" + str + "']";
    $('#CommentBox').val(comment_text);
    closeModal();
}

// Play BAFTA video in modal
function baftaVideo(key)
{
  var vids = {
        baftaArt1: {video: 'ART_DIRECTOR.mp4', title: 'Art Director'},
        baftaArt2: {video: 'ANIMATION_DIRECTOR.mp4', title: 'Animation Director'},
        baftaEdit1: {video: 'EDITOR.mp4', title: 'Editor'},
        baftaComposer1: {video: 'COMPOSER.mp4', title: 'Composer'},
        baftaWriter1: {video: 'WRITER.mp4', title: 'Scriptwriter'},
        baftaStudio1: {video: 'DIRECTOR.mp4', title: 'Director'}
      },
      modalContent = $('<div id="standardModal"> <div class="inner cfx"> <div id="baftaVideoViewer"> <h1 class="pageTitle">Bafta video title</h1> <div id="baftaVideoContainer"> </div> <a href="#" title="close" class="close closeIcon">close</a> </div> </div> </div>');
  if(vids[key])
  {
    $('.pageTitle', modalContent).text(vids[key].title);
    flowplayer($('#baftaVideoContainer', modalContent)[0], {src: "/flowplayer/flowplayer-3.2.2.swf", wmode: 'transparent'}, "/video/"+vids[key].video);
    $.modal(modalContent);
    _gaq.push(['_trackEvent', 'Bafta Video', vids[key].video]);
    if(!$('#muteLink a').hasClass('true'))
    {
      $('#muteLink a').click();
    }
  }
}

function overlayOutboundLink(url, text) {
	modalContent = $('<div id="standardModal"><div class="inner cfx"><div id="imageModal"><img src="/img/director.gif" alt="" class="helper" /><h1 class="replace pageTitle">Leave this website?</h1><p class="buttons"><a class="button close" href="#"><span class="close">No thanks</span></a><a class="button on okButton" href="#"><span>OK</span></a></p></div></div></div>');
	$('.okButton', modalContent).attr('href', url);
	if (text) {
		$('.pageTitle', modalContent).text(text);
	}
	$.modal(modalContent);
}

// $(document).ready(function() {
// 	var data = [{ "name":"Directors Room",  page: "home"}, { "name":"Art Studio",  page: "art_room"}, { "name":"ANIMATION TOOL",  page: "animation_tool"}];
// 	updateBreadCrumb(data);
// });

