$(document).ready(function() {

//news fader in footer panel
$(".news_fader").CarouSlide({
			animType:"fade",
			animInfinity:true,
			showSlideNav:false,
			autoAnim:true,
			showPauseButton:false,
			showBackNext:true,
			animTime:1000,
			slideTime:4000,
			sliderHolder: ".news_fade_holder",
			easingStyle: "custom"
});

//disabled - only using single images atm.
$("#banner").CarouSlide({
			animType:"fade",
			animInfinity:true,
			showSlideNav:false,
			autoAnim:false,
			showPauseButton:false,
			showBackNext:false,
			animTime:1000,
			slideTime:6000
});

//used on the work item pages.
	$('.gallery').isotope({
  		itemSelector: '.gallery_image',
		masonry : {
          columnWidth : 248
        },
		animationOptions: {
     			duration: 750,
     			easing: 'linear',
     			queue: false
   		}
	});

	
	var $container = $('#portfolio'),
          // object that will keep track of options
          isotopeOptions = {},
          // defaults, used if not explicitly set in hash
          defaultOptions = {
            filter: '*',
            sortBy: 'date',
            sortAscending: false,
            layoutMode: 'fitRows'
          };
 

  
      var setupOptions = $.extend( {}, defaultOptions, {
        itemSelector : '.portfolio_item',
        layoutMode : 'masonry',
        masonry : {
          columnWidth : 248
        },
        getSortData : {
          category : function( $elem ) {
            return $elem.attr('data-category');
          },
          date : function( $elem ) {
            return parseInt( $elem.find('.date').text(), 10 );
          },
          name : function ( $elem ) {
            return $elem.find('.category').text();
          }
        }
      });
      
      
  
      // set up Isotope
      $container.isotope( setupOptions );
  
      var $optionSets = $('#options').find('.option-set'),
          isOptionLinkClicked = false;
  
      // switches selected class on buttons
      function changeSelectedLink( $elem ) {
        // remove selected class on previous item
        $elem.parents('.option-set').find('.selected').removeClass('selected');
        // set selected class on new item
        $elem.addClass('selected');
      }
  
      $('.option-set a').click(function(){
      // get href attr, remove leading #
  		var href = $(this).attr('href').replace( /^#/, '' ),
      // convert href into object
      // i.e. 'filter=.inner-transition' -> { filter: '.inner-transition' }
      option = $.deparam( href, true );

  // set hash, triggers hashchange on window
  $.bbq.pushState( option );
  return false;
});
      
$(window).bind( 'hashchange', function( event ){
  // get options object from hash
  var hashOptions = $.deparam.fragment(),
  // gets the string from hash and cleans it up (for readability)
  filterOption = $.param.fragment(),
  cat = filterOption.replace("filter=.",""), 
  catClearUp = cat.replace("_"," ");
  
  // apply options from hash
  $container.isotope( hashOptions );
  
  var pageNameForGA = 'Work - Category: '+ cat;
  
  if(pageNameForGA != 'Work - Category: '){
  	_gaq.push(['_trackPageview', pageNameForGA]);
  	console.log(pageNameForGA)
  }
  //writes the new category name
  if(catClearUp != ""){
  	$('.title_slash_work').after('<span class="work_title">'+catClearUp+'</span>');
  	$('.work_title:first').fadeIn(200).siblings('.work_title').fadeOut(200, function(){$(this).detach()});
  }else{  	
  	$('.title_slash_work').after('<span class="work_title">Our Work</span>');
  	$('.work_title:first').fadeIn(200);
	}
	//adds a current class to the active sub nav (only in work atm)
	$('.workNav li a[href="#'+filterOption+'"]').parent('li').addClass('current').siblings('li').removeClass('current');
  
})
  // trigger hashchange to capture any hash data on init
  .trigger('hashchange');
  
   

//custom easing	
	$.easing.custom = function (x, t, b, c, d, s) {
		if (s == undefined) s = 0;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	}
 
//Home page scoller

if ($(".scrollable").length == 1){
	$(".scrollable").scrollable({easing: 'custom', circular: true, speed: 900}).navigator({naviItem: '.nav_items', navi: '.navi'}).autoscroll({interval:9000, autoplay:false});
	
	var api = $(".scrollable").data("scrollable");
	api.seekTo(4,0);	
	api.move(-4,7000);
	
	setTimeout(function() {
		api.play();
		$('.banner_tabs .nav_items:first').addClass('active');
  }, 7000);
}



	var wh = $(window).height();
		
	if (wh <= 640){		
		scrollPromptInOut();
	}else{
		fadeTopInOut();
	}


	//Top button fader
	$('#topBTN').click(function(){
        	$('html, body').animate({scrollTop:0}, 'slow');
        	return false;
    });
	
	// Show top button on scroll
	function fadeTopInOut() {
		$(window).scroll(function(){  
			  if($(window).scrollTop() > 500){
			    $('#topBTN').fadeIn(100);
			  }else{
			    $('#topBTN').fadeOut(100);
			  }
		});
	}
	
	function scrollPromptInOut() {
		$('#fold').fadeIn(100);
		$(window).scroll(function(){ 
			var st = $(window).scrollTop() 
			  if(st > 150){
			    $('#fold').fadeOut(100);
			  }else{
			  	$('#fold').fadeIn(100);
			  }
			  
			  if (st > 500){
			    $('#topBTN').fadeIn(100);
			  }else{
			    $('#topBTN').fadeOut(100);
			  }
		});
	}
	
	

	//updated hover event for portfolio items (fix for ie mostly)
	$(".hover").hover(function(){
		$(this).children('.back').fadeIn(200);
	},function(){
		$(this).children('.back').fadeOut(200);
	});
	


	$('.fade_section').each(fadeInSection);
	function fadeInSection(i){
		$(this).delay(i*500).fadeTo(500,1);
	};
	
	$(".back").fadeOut(200);


//subscription page form
function checkEmail(email) { 
  var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var emailVal = $("#" + email).val();
  return pattern.test(emailVal);
}


$('#subForm').submit(function(e) {
  e.preventDefault();
        
  // Grab form action
  var formAction = this.action;
  
  // Hacking together id for email field
  // Replace the xxxxx below:
  // If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
  var id = "nurtyd";
  var emailId = id + "-" + id;
  
  // Validate email address with regex
  if (!checkEmail(emailId)) {
    alert("Please enter a valid email address");
    return;
  }
  
  // Serialize form values to be submitted with POST
  var str = $(this).serialize();
  
  // Add form action to end of serialized data
  // CDATA is used to avoid validation errors
  //<![CDATA[
  var serialized = str + "&action=" + formAction;
  // ]]>
  
  // Submit the form via ajax
  $.ajax({
    url: "/proxy.php",
    type: "POST",
    data: serialized,
    dataType: 'html',
    success: function(data){
      // Server-side validation
      /*
if (data.search(/invalid/i) != -1) {
        alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
      }
      else
      {
*/
        var $confirmation = $('#confirmation');
        $("#subForm").hide(); // If successfully submitted hides the form
        $confirmation.slideDown("slow");  // Shows "Thanks for subscribing" div
        $confirmation.prop('tabIndex', -1);
        $confirmation.focus(); // For screen reader accessibility
        // Fire off Google Analytics fake pageview
        //var pageTracker = _gat._getTracker("UA-XXXXX-X");
        //pageTracker._trackPageview("/newsletter_signup");
      /* } */
    }
  });
});



//google map stuff
var map;
function initialize() {
	var latlng = new google.maps.LatLng(-34.949435,138.630729);
	var myOptions = {
		zoom: 14,
		center: latlng,
		streetViewControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);	
	setMarkers(map, BMD);	
		
	$('.adel_btn').click(function(){
		$('.map').fadeTo(500,1);
		var lat = -34.949435;
		var lon = 138.630729;
		var a = new google.maps.LatLng(lat,lon);
		map.setCenter(a);
		google.maps.event.trigger(map, 'resize');
		return false;
	})
	
	$('.gold_btn').click(function(){
		$('.map').fadeTo(500,1);
		var lat = -28.089876;
		var lon = 153.449977;
		var b = new google.maps.LatLng(lat,lon);
		map.setCenter(b);
		google.maps.event.trigger(map, 'resize');
		return false;
	})
	
	google.maps.event.trigger(map, 'resize');
}

var BMD = [
  ['Adelaide', -34.949435,138.630729],
  ['Gold Coast', -28.089876,153.449977]
];

function setMarkers(map, locations) {	
	var image = new google.maps.MarkerImage('/images/icon.png',
	  new google.maps.Size(50, 69),
	  new google.maps.Point(0,0),
	  new google.maps.Point(25, 69)
	);
	for (var i = 0; i < locations.length; i++) {
	var BMD = locations[i];
	var myLatLng = new google.maps.LatLng(BMD[1], BMD[2]);
	var marker = new google.maps.Marker({
	    position: myLatLng,
	    map: map,
	    icon: image,
	    title: BMD[0]
		});
	}	
}

if ( $('.map').length == 1 ){
	initialize();
}


});
	
	 
