
	var windowWidth;
	var windowHeight;
	var ratioOver = 1;
	var ratioUnder = 1;		
	
	//Analytics
  /*var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-12101328-1']);
  _gaq.push(['_trackPageview']);
 
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();*/
 


	//Fullscreen ratio preserved BG - credit: Cactus Lab
	function resetSizes(){
		windowWidth = $(window).width();
		windowHeight = $(window).height();
	}
	
	function imgWindowRatio(){
		var $background = $('#scale img');		
		var imgWidth = $background.width();
		var imgHeight = $background.height();
		ratioOver = imgWidth / imgHeight;
		ratioUnder = imgHeight / imgWidth;		
		if((windowWidth / windowHeight) >= ratioOver) {
			return 'taller';
		} else {
			return 'wider';
		}
	}
	
	function scaleBackground(){
		var $background = $('#scale img');
		if(imgWindowRatio() == 'taller'){
			$background.css('width',windowWidth);
			$background.css('height',Math.floor(ratioUnder*windowWidth));
		} else {
			$background.css('width',Math.floor(ratioOver*windowHeight));
			$background.css('height',windowHeight);
		}
	}
	
	function resizeElements(trigger){
		resetSizes();			
		scaleBackground();
	}

	
	function refigure(trigger){		
		resizeElements(trigger);
		if($.browser.mozilla){
			setTimeout(function() {
				resizeElements(trigger);
			}, 50);
		}
	}
	
		
		function setBackground(url){            	
			var $bgImage = $('#scale img.bg');							
			//if($.address.baseURL()+'/'+url == $bgImage.attr('src')) {return};// check if image is same	
			var $newBg = $bgImage.clone().attr('src', url);
			$bgImage.remove();
			$newBg.appendTo('#scale').hide();			
			$('#loading').show();							
			$('#scale').onImagesLoad({ selectorCallback: function(){
				$('#loading').hide();
				$newBg.fadeIn('slow');
			}});			
		}

		
		function homepageSlideshow(){
						$('.homepage-slideshow').cycle({
							fx: 'scrollLeft',
							easing:'easeOutQuint',
							pause: true
						});
    				$('.homepage-hover').hide();
    				$('.homepage-slideshow li').hover(
    							function(){
    										if($.browser.msie){// avoid ie png fade fail
													$(this).children('.homepage-hover').show(); 
												} else {
    											$(this).children('.homepage-hover').fadeIn("fast");
    										}
    							},function(){
    										if($.browser.msie){// avoid ie png fade fail
													$('.homepage-hover').hide(); 
												} else {
    											$(this).children('.homepage-hover').fadeOut("fast");
    										}
    							}
    				);
    }
    
    function projectSlideshow() {
    				$('.project-slideshow').cycle({
							fx: 'fade', 
							next: '.next',
							prev:'.prev',
							pause: true, // pause on hover
							requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded 
    					requeueTimeout: 1250,   // ms delay for requeue 
							timeout:4000
						});
						var alphaTo = 1;
						if($.browser.msie){alphaTo=.8} 
						$('.prev').css( {backgroundPosition: "-80 0", opacity:0} ).hover(
							function(){								
								$(this).stop().animate(
									{backgroundPosition:"(0 0)", opacity:alphaTo}, 
									{duration:200},
									{easing:'easeOutQuint'})
							}, function(){
								$(this).stop().animate(
									{backgroundPosition:"(-80 0)", opacity:0}, 
									{duration:500},
									{easing:'easeOutQuint'}
									)
						});
						$('.next').css( {backgroundPosition: "352 0", opacity:0} ).hover(
							function(){
								$(this).stop().animate(
									{backgroundPosition:"(232 0)", opacity:alphaTo}, 
									{duration:200},
									{easing:'easeOutQuint'})
							}, function(){
								$(this).stop().animate(
									{backgroundPosition:"(352 0)", opacity:0}, 
									{duration:500},
									{easing:'easeOutQuint'})
						});
		}
	
	
		function workRollOvers(){
						$('.work-hover').hide();
    				$('.project').hover(
    						function(){
    								if($.browser.msie){// avoid ie png fade fail
												$(this).children('.work-hover').show(); 
										} else {
    										$(this).children('.work-hover').fadeIn("fast");
    								}
    						},function(){
    								if($.browser.msie){// avoid ie png fade fail
												$(this).children('.work-hover').hide(); 
										} else {
    										$(this).children('.work-hover').fadeOut("fast");
    								}
    						}
    				);

		}
		
		function workFilters() {
					$('.allfilter').hide();
    			$('.filter').hover(
    						function(){
    								$(this).css({color:"#CCCCCC"})
    						},function() {
    								$(this).css({color:"#FFFFFF"})
    						}
    			);
    			$('.filter').css('cursor',"pointer").click(
    					function(){
    						var $filter = $(this).text().toString();
    						$('.all').each(function (i) {
    									if ( $(this).hasClass($filter) ){
    												$(this).fadeIn("slow");
    									} else {
    										$(this).fadeOut("slow");
    									}
    						});	
    					if ($filter === 'all') {$('.allfilter').hide();} else {$('.allfilter').show();}   					
    			});
		
		}
		
		function submitRollOvers() {		
		 $('#submit1').hover(
            function(){ // Change the input image's source when we "roll on"
                $(this).attr({ src : 'images/btn-signup-over.png'});
            },
            function(){ // Change the input image's source back to the default on "roll off"
                $(this).attr({ src : 'images/btn-signup.png'});             }
        );
        
       $('#submit2').hover(
            function(){ // Change the input image's source when we "roll on"
                $(this).attr({ src : 'images/btn-send-over.png'});
            },
            function(){ // Change the input image's source back to the default on "roll off"
                $(this).attr({ src : 'images/btn-send.png'});             }
        );		
		}
		
		function formValidation() {
		var trap = $("input#f_comments").val();
    				var options = {
        		beforeSubmit: function() {
        			if (trap != "") {
    						alert('Uh Oh! It appears you have filled in a hidden field!');
    						return false;//nasty spambots can get fucked.
							}
            		return $('#contact').validate().form();            	
        		},
        		url: 'mailr.php',        		
        		success: successfunc
   				 };

    				$('#contact').ajaxForm(options);
    				
    				function successfunc() {
        							$('.contact-fields').html("<div id='message'></div>");
        							$('#message').html("<h3 class='antenna'>Thanks for your enquiry!</h3>")
        							.append("<p>We will be in touch soon.</p>")
       							 	.hide()
        							.fadeIn("slow");
        							$('#submit2').hide();
      			}
		}
		
		function journalSearch() {
		
		$('.button').hover(
            function(){ // Change the input image's source when we "roll on"
                $(this).attr({ src : 'images/btn-search-over.png'});
            },
            function(){ // Change the input image's source back to the default on "roll off"
                $(this).attr({ src : 'images/btn-search.png'});
            }
     );
		
		 $(".tbutton").click(function() {
      				var query = $('#q').val();
      				var querypath = '/journal/?q='+query;
      				$.address.value(querypath)
      				return false;
    				});

		
		}
		
				

			
            
      
          
  // Init and change handlers
  $.address.change(function(event) {
	
  	$('#scale img.bg').fadeOut('fast');
  
  	$('#content').fadeOut('slow',loadContent);
  	
  	 
  	var sectionArray = $.address.pathNames();
  	var section = sectionArray[0];
           
  	$('.nav li a').each(function() {//COLOR SELECTED NAV TEXT             
             linktext = $(this).text()  
              $(this).toggleClass('selected', linktext.toLowerCase()==section);
    });

  		     
  
  
  
      		function loadContent(){
    				//refigure();
    				$("#content").load('datasource.php?swfaddress=' + event.path,'',showContent);
   				}	
    			
    			function showContent() { //CONTENT
    			
    				if($.browser.msie && $.browser.version=="7.0"){
    				//ajax deeplinking doesnŐt work in IE 7     				
    				}else{    			
    					$('a:not(.external)').address(function() {  
     						return $(this).attr('href').replace(/^#/, ''); // ajax non external links 
 							});
 						}  				
    				
    				$.address.title($('#content .bg').attr('alt')); //set title
    				var $bgURL = $('#content .bg').attr('src') ;   //setBG  
    				$('#content .bg').remove();//removes bgimage loaded in content.xml
    				$('#content').fadeIn('normal');    				
    				setBackground($bgURL);
    				
    				if ($('.homepage-slideshow').length != 0){ 
    				homepageSlideshow();
    				}
    				if ($('.project-slideshow').length != 0){ 
    				projectSlideshow();
    				}
    				if ($('.project').length != 0){ 
    				workRollOvers();
    				}
    				if ($('.filter').length != 0){ 
    				workFilters();
    				}
    				if ($('#contact').length != 0){ 
    				submitRollOvers();
    				formValidation();
    				}
    				if ($(".button").length != 0){
    				journalSearch();
    				}
    				    				
    				if($.browser.msie){
    						$('.heading').dropShadow();
     				}
     				  			
						
    				//$('textarea').autogrow();
    			refigure();
    				//googleTracking();
    			
    			pageTracker._trackPageview(event.value);
    				
    			//Video
    			if ($('#video').length != 0){     				
  					var so = new SWFObject('video/vidplayer.swf','mpl','634','357','9');
  					so.addParam('allowfullscreen','true');
  					so.addParam('allowscriptaccess','always');
  					so.addParam('wmode','opaque');
  					so.write('video');	
					}

    			   			
         /* var names = $.map(event.pathNames, function(n) {
                    return n.substr(0, 1).toUpperCase() + n.substr(1);
          }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
          var links = names.slice();
          var match = links.length ? links.shift() + ' ' + links.join('.') : 'Home';
          $('a').each(function() {
              $(this).toggleClass('selected', $(this).text() == match);
          });
    				*/   
   			 	}
   			 		
     				
     			refigure();
   			 	
   			 
                               
	});
            
function googleTracking() {
$('a').click(function () {
							var thisel = $(this);
							try {_gaq.push(['_trackEvent', thisel.parents('[id!=""]:first').get(0).id, 'clicked', (thisel.text() || thisel.children('img:first').attr('alt'))]);} catch (err) {}
							});

}
	
	
	
	
	
	
	
	
	function init() {
	//asynchronus google tracking event
						googleTracking();							
		
							
		$('#content').hide();  
    $('.nav_credits').hover(function() {
    		$('.nav-photo-hover').fadeIn('fast')},function() {
        $('.nav-photo-hover').fadeOut('fast')
    })
                 
		$('.bg').hide();
		windowWidth = $(window).width();
		windowHeight = $(window).height();
						
		// GENERAL		
		$(window).resize(function(){
			refigure('resize');
		});
	}

	
	
$(function() {
	init();
});
