$(document).ready(function(){
  $.ajaxSetup( { 
    complete: function () {
      afterAjax()
    },
    beforeSend: function () {
      beforeAjax()
    }
  });
  
  //$('#footer-bg').empty() ? $('#footer-bg').hide() : "";
  
  $('.fancybox').fancybox({
   'width' : 700,
   'height' : 500,
   'autoScale' : false,
   'transitionIn' : 'none',
   'transitionOut' : 'none',
   'type' : 'iframe',
   'scrolling' : 'no',
   'titleShow' : false
  });

  /******** form js *********/
  $( ".datepicker" ).datepicker({
    dateFormat: 'dd/mm/yy',
    onClose: function() { 
      val = $(this).val(); 
      $(this).focus();
      $(this).val(val);
      $(this).blur();
    }
  });
  
  $(".frm_example").example();     
  
  //custom select box
  $(".sb").sb();
  /****************************/

  $("#home-case-studies .inner").jCarouselLite({
    btnNext: "a.btn.next",
    btnPrev: "a.btn.prev",
    auto: 6000,
    speed: 1000,
    visible: 4,
    scroll: 1
  }); 

  $("#home-case-studies .inner").css("width","920");  
  
  initSlider();
  initNavSub();

  $('html.no-csstransitions nav#primary ul li a:not(".active")').css('background-color', 'inherit');

  $('html.no-csstransitions nav#primary ul li a:not(".active")').hover(
    function () {
      $(this).animate(
        {backgroundColor: '#80a5c2'},
        200, 'linear'
      );
    },
    function () {
      $(this).stop().css( {backgroundColor: 'transparent'});
    }
  );

  homeBoxLinks();

});

function beforeAjax() {
	$.fancybox.showActivity();
}

function afterAjax() {
	$.fancybox.hideActivity();	
}





var timer = false;
var start_timer = false;

$(document).ready(function() {
  if ($('.hash-nav ul a').length) {
    $('.hash-nav ul a').click(function (e) {
      if ($(this).attr('href').substring(0, 1)=='#') {
        e.preventDefault();
        location.hash="_" + $(this).attr('href').replace('#', '');
      }
    });

    $(window).bind( "hashchange", function(e) {
    
      e.preventDefault();
      hash = e.fragment.replace('_', '');
      $.smoothScroll({scrollTarget: $('a[name=' + hash + ']').add('[id=' + hash + ']'), offset: -10 } );

    });

  }
  $('.slideshow #main-image').bind('load', function() {$(this).fadeIn(500);});
  $('ul.slideshow-thumbs li a').not('#view_gallery').each(function() {
    $(this).click(function(event, auto) {
      event.preventDefault();
      if (typeof(auto) == 'undefined') {
        window.clearInterval(timer);
        window.clearInterval(start_timer);
      }
      var rel = $(this).text();
      var src = $(this).attr('href');
      $('.slideshow #main-image').fadeOut(250, function () {$(this).attr('src', src).attr('rel', $(this).text())});
      if (typeof(auto) == 'undefined' && $('ul.slideshow-thumbs li a').not('#view_gallery').size()>1) {
        start_timer = window.setTimeout('startCaseStudyTimer()', 5000);
      }
    });
  });
  if($('ul.slideshow-thumbs li a').not('#view_gallery').size()>1) {
    startCaseStudyTimer();
  }
});

function startCaseStudyTimer() {
  timer = window.setInterval("displayNextCaseStudy()", 5000);
}


function displayNextCaseStudy() {
  var found = false;
  var done = false;
  $('ul.slideshow-thumbs li a').not('#view_gallery').each(function () {
    if (found) {
      $(this).trigger('click', [ true ] );
      done = true;
      found = false;
    }
    
    if (!done && $(this).attr('href') == $('#main-image').attr('src')) {
      found = true;
    }
  })
  if (!done) {
    $('ul.slideshow-thumbs li a').not('#view_gallery').first().trigger('click', [ true ] );
  }

}

//scroll back to top
$(document).ready(function() {
    var t = $('<div class="primary-back-to-top"></div>'),
    d = $(document);
    $('body').append(t);

    t.css({
      opacity: 0,
      position: 'absolute',
      top: 0,
      right: '5%'
    });

    t.click(function() {
      $('html,body').animate({
        scrollTop: 0
      }, 1000);
    });

    $(window).scroll(function() {
      var sv = d.scrollTop();
      if (sv < 120) {
        t.clearQueue().fadeOut(200);
        return;
      } else {
        t.css('display', '').clearQueue().animate({
          top: sv,
          opacity: 0.6
        }, 500);
      }
    });

		$("#view_gallery").click(function() {
      var imagesrcs = $(this).attr('rel');
      var images = imagesrcs.split(',');
			$.fancybox(images, {
				'transitionIn'		: 'elastic',
				'transitionOut'		: 'elastic',
				'easingIn'			: 'easeOutBack',
				'easingOut'			: 'easeInBack',
				'type'              : 'image'
			});
		});
}); 

function homeBoxLinks() {
  $('article#home-products>ul>li a.imagelink').click(function(event) {
    event.stopPropagation();
    window.location = $(this).attr('href');
  })
  $('article#home-products>ul>li').click(function () {
    $(this).find('a.imagelink').click();
  }).css('cursor', 'pointer');
}

function initNavSub() {

  var nav_sub = $("nav#sub");

  if (nav_sub.length) {

    var nav_sub_pos = nav_sub.position();

    var holder = $('<div>&nbsp;</div>');

    holder.css({
      'width': nav_sub.width(),
      'height': nav_sub.height(),
      'display': nav_sub.css('display'),
      'float': nav_sub.css('float'),
      'margin-left': nav_sub.css('margin-left'),
      'margin-top': nav_sub.css('margin-top'),
      'padding-top': nav_sub.css('padding-top'),
      'padding-right': nav_sub.css('padding-right'),
      'padding-bottom': nav_sub.css('padding-bottom'),
      'padding-left': nav_sub.css('padding-left'),
      'clear': 'left'
    });

    nav_sub.after(holder);

    nav_sub.css({
      'position': 'absolute',
      'top': nav_sub_pos.top,
      'left': nav_sub_pos.left
    });

    $(window).scroll(function () {
      topoffset = Math.max(nav_sub_pos.top, $(window).scrollTop());
      topoffset = Math.min(topoffset, (nav_sub.parent().height() + nav_sub.parent().position().top) - (nav_sub.height() + nav_sub.parent().find('#twitterings').height() + 105 + ($('#coffee-chat').length ? 260 : 0)) );

      $("nav#sub").stop().animate({
        top: topoffset
      });
    }).scroll();

    $(window).resize(function () {
      $("nav#sub").css({
        'left': holder.position().left
      });
    });
  }
}

function initSlider() {

  $("nav#sub.portfolio-nav ul li a, .portfolio-list li a").click(function(event) {
    if ($('.portfolio-list a[href="' + $(this).attr('href') + '"]').length && $(this).attr('href').substr(0, 1) != '#' ) {
      event.preventDefault();
      location.hash = '!' + $(this).attr('href');
    } else if ($('.portfolio-list a[name="' + $(this).attr('href').replace('#', '') + '"]').length) {
      event.preventDefault();
      url = $(this).attr('href').replace('#', '');
      $(this).closest('ul').find('li a').removeClass('active');
      $.smoothScroll({scrollTarget: $('a[name=' + url + ']').add('[id=' + url + ']') });
      $(this).addClass('active');
    }
  });

	$(window).bind( "hashchange", function(e) {
	  var url = e.fragment.replace('!', '');
    if (url.length) {
      sliderAjax(url);
    }
	}).trigger('hashchange');

}

function sliderAjax(url) {


  var el = $('.portfolio-list a[href="' + url + '"]');

  if (el.length) {

    var leftnav = $('nav#sub ul li a[href="' + url + '"]');
    var container = el.parent('li');
    var url = el.attr('href');

    el.closest('ul').find('section:visible').slideUp(500);
    el.closest('ul').find('a.slink').removeClass('selected');
    el.addClass('selected');
    $('nav#sub ul li a, nav#sub ul li').not(leftnav).removeClass('active').parent().find('ul').addClass('closed');
    leftnav.addClass('active');
    leftnav.parent().find('ul').removeClass('closed');
    if (container.children().length == 1) {
      content = $.get('/ajax' + url, function (response, status) {
        el.parent().append(response).find('section').slideDown(500, function () { $.smoothScroll({scrollTarget: $('a.slink.selected').closest('li'), offset: -10});}).find('h1:first').remove();
      } );
    } else {
      container.find('section').slideDown(500, function () { $.smoothScroll({scrollTarget: $('a.slink.selected').closest('li'), offset: -10 });});
    }

  }

}















