var banners = ['tracking', 'shirt-08', 'national', 'callcommand', 'global'],
  currentBanner = 0,
  intervalId = 0,
  mainmenuId = 0;
  
$(document).ready(function() {
  
  $('div#banner').removeClass().addClass($('#banner div:first-child').attr('id'));
  $('div#banner div:first-child').addClass('current');
  
  window.___gcfg = {lang: 'en-GB'};
    
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
  
  if($('span.sub span').length) {
    $('span.sub span iframe').attr('frameBorder','0');
    $('span.sub span iframe').attr('border','0');
    $('span.sub span iframe').attr('scrolling','no');
  }

  //$('#banner').addClass('tracking');

  
  // $(document).pngFix(); 
  
  Cufon.replace('h1, h2, h3, div#head p, p.section-header, div.site-width a.tab',{
    hover: true
  });
  
  if (typeof ItemEditing == 'undefined') {
    $('#map').each(function() {
      
      $(this).addClass('mapdimensions');
      var mapId = $(this).attr('id');
      
      var value = $(this).html();
      value = $.trim(value);
      
      var point = value.split(',');

      var lat = parseFloat(point[0]);
      var lon = parseFloat(point[1]);
      var zoom = parseFloat(point[2]);
      
      maps = new GMap2(document.getElementById(mapId));
      
      var p = new GLatLng(lat, lon);
      maps.setCenter(p, zoom); 
        
      // Create Core marker
      var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image = "/images/gmap-icon.png";
        blueIcon.transparent = "/images/gmap-icon.png";
        blueIcon.iconSize = new GSize(62, 62);
        blueIcon.iconAnchor = new GPoint(31, 59);
      
      // Add marker to map
      markerOptions = { icon:blueIcon };

      var marker = new GMarker(p, markerOptions);
      maps.addOverlay(marker);  
      
      maps.addControl(new GSmallMapControl());
      maps.addControl(new GMapTypeControl());
    
      // GEvent.addListener(marker,"click", function() {
      // // alert('clicked marker');;
      // var myHtml = "Address?";
        // marker.openInfoWindowHtml(myHtml);
      // });
      
    });
  }
  
  //Clients Sidebar Slider
  if($('#clients').length) {
    
    var slider = $('#clients div');
    
    slider.before('<a class="prev" href="#"></a>');
    slider.after('<a class="next" href="#"></a>');
    $('#clients ul li').css('float','left');
            
    $('#clients a.next').click(function() {
      if(!$('#clients ul li.current').next('li').length) {
        $('#clients ul li').removeClass('current');
        $('#clients div')
        .scrollTo(
          $('#clients ul li:first-child')
          .addClass('current'), 600, {
            easing: 'easeinout'
          }
        );
        return false;
      } else {
        $('#clients div')
          .scrollTo(
            $('#clients ul li.current')
            .removeClass('current')
            .next('li')
            .addClass('current'), 400, {
              easing: 'easeinout'
            }
          );
        return false;
      }
    });
    $('#clients a.prev').click(function() {
      if(!$('#clients ul li.current').prev('li').length) {
        $('#clients ul li').removeClass('current');
        $('#clients div')
        .scrollTo(
          $('#clients ul li:last-child')
          .addClass('current'), 600, {
            easing: 'easeinout'
          }
        );
        return false;
      } else {
        $('#clients div')
          .scrollTo(
            $('#clients ul li.current')
            .removeClass('current')
            .prev('li')
            .addClass('current'), 400, {
              easing: 'easeinout'
            }
          );
        return false;
      }
    });
  }
  
  // Check 'confirm email address' in revenue box CM 14102011
  if ($('#revenue-form').length) {
    var rf = $('#revenue-form'),
        emailInput = rf.find('.email input'),
        confirm = rf.find('.confirmemail'),
        confirmInput = confirm.find('input'),
        errorBox = $(document.createElement('span')).addClass('contourError').text('Email address does not match').css('display','none');
    confirm.append(errorBox);
    confirmInput.bind('blur', function(e) {
      console.log(confirmInput.val(), emailInput.val());
      if (confirmInput.val() != emailInput.val()) {
        errorBox.css('display','inline');
        confirmInput.focus();
      } else {
        errorBox.css('display','none');
      }
    });
    
  }
  
  //Social share links
  $('article aside a').click(function(){
    window.open($(this).attr('href'),'Share','width=500,height=500,resizable=no,scrollbars=yes,status=1');
    return false;
  });
  
  //Animate top nav
  if((!navigator.userAgent.match(/iPhone/i)) || (!navigator.userAgent.match(/iPod/i))) {
    
    if($('nav#top-nav').length) {
      $("nav#top-nav ul").lavaLamp({
        fx: "easeinout",
        speed: 500
      });
    }

  }
  
  //Animate anchors
  if($('#main-content').length) {
    $('#main-content').localScroll({
      easing: 'easeinout',
      speed: 1300
    });
  }
  
  if($('div#profiles').length){$('div#profiles').hide();}
  
  // FANCY BOX
  if ($('div.team.box-list div a').length) {
    $('div.team.box-list div a').each(function(){
      $(this).fancybox({
        'content' : $("#div-"+$(this).attr('id')).html(),
        'scrolling':'no',
        'titleShow':false,
        'autoScale':false
      });
      $.fancybox.resize;
    });
  }
  // END FANCY BOX
  
  if($('ul.tabs').length) {
    //Default Action
    $(".tab-content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab-content:first").show(); //Show first tab content
    
    //On Click Event
    $("ul.tabs li").click(function() {
      $("ul.tabs li").removeClass("active"); //Remove any "active" class
      $(this).addClass("active"); //Add "active" class to selected tab
      $(".tab-content").hide(); //Hide all tab content
      var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
      $(activeTab).fadeIn(); //Fade in the active content
      return false;
    });
  }
    
  var formHeight = $('div#head div form').css('height');
    
  //Client Login  
  // $('div#head div form').css({'height':0});
  // $('div#head div').css({'top':$('div#head div').height()*-1}).delay(1000).animate({'top':0}).click(function(e) {
    // e.preventDefault();
    // var clientForm = $(this).children('form');
    // if (clientForm.height() === 0) {
      // clientForm.animate({'height':formHeight, 'padding-top':6, 'padding-bottom':6});
    // } else {
      // clientForm.animate({'height':0, 'padding-top':0, 'padding-bottom':0});
    // }
  // });
  
  // LOGO WHEEL //
  if($('#logo-wheel').length) {
    var liWidth = $('#logo-wheel li').width(),
      logoCount = $('#logo-wheel ul').children('li').length-1,
      currentPos = $('#logo-wheel .current').position().left;
  }
  
  resetBanner(moveBannerIn);
  intervalId = setInterval(switchBanners, 10000);
  //mainmenuId = setInterval(function() {$('#logo-wheel .next').click()}, 2000);
  
  if($('#logo-wheel').length) {
    //Check which version of logo wheel you are looking at
    if($('#main-content #logo-wheel').length) {
      ulWidth = 695;
    } else {
      ulWidth = 980;
    }
    $('#logo-wheel ul').css('left', 53+(currentPos*-1)+((ulWidth-liWidth)/2));
    $('#logo-wheel .back, #logo-wheel .next').click(function(e) {
      // Interrupt auto scroll
      clearInterval(mainmenuId);
      scrollLogos(e);
    });
  }
  // END LOGO WHEEL //
  
  // Apply shadow to 'sections'
  $('#main-content section').each(function() {    
    box = $(this);
    boxPos = box.position();
    shadow = $(document.createElement('img'));
    shadow
      .addClass('box-shadow')
      .css({'left':boxPos.left-8, 'top':boxPos.top+box.height()-35})
      .attr('src', '/images/box-shadow.png');
    box.after(shadow);
  });
  $('#home-content section').each(function() {    
    box = $(this);
    boxPos = box.position();
    shadow = $(document.createElement('img'));
    shadow
      .addClass('box-shadow')
      .css({'left':boxPos.left-8, 'top':boxPos.top+box.height()-35})
      .attr('src', '/images/box-shadow.png');
    box.after(shadow);
  });
  
  // Apply shadow to home sidebar
  $('#home-sidebar').each(function() {
    box = $(this);
    boxPos = box.position();

    shadow = $(document.createElement('img'));
    shadow
      .addClass('box-shadow sidebar')
      .css({'left':boxPos.left+25, 'top':boxPos.top+box.height()+80})
      .attr('src', '/images/sidebar-box-shadow.png');
    box.after(shadow);
  });

});

function scrollLogos(e) {
  var clicked = e ? $(e.currentTarget).attr('class') : 'next',
    liWidth = $('#logo-wheel li').width();
    prevEl = $('#logo-wheel .pre').prev(),
    preEl = $('#logo-wheel .pre'),
    currentEl = $('#logo-wheel .current'),
    postEl = $('#logo-wheel .post'),
    nextEl = postEl.next(),
    logoCount = $('#logo-wheel ul').children('li').length-6,
    leftPos = $('#logo-wheel ul').position().left,
    queue = $('#logo-wheel ul').queue().length;

  if (queue > 0) {
    //$('#logo-wheel ul').queue([]);
    return false;
  }
  
  if (leftPos <= -1*logoCount*liWidth) {
    // Copy first LI and add to end
    $('#logo-wheel ul').append($('#logo-wheel li:first-child').clone()).css({'left':leftPos+liWidth});
    $('#logo-wheel li:first-child').remove();
  }
  if (leftPos > 0) {
    // Copy last LI and add to start
    $('#logo-wheel ul').prepend($('#logo-wheel li:last-child').clone()).css({'left':leftPos-liWidth});
    $('#logo-wheel li:last-child').remove();
  }
  
  //Set widths depending on which version of logo-wheel you can see
  if($('#main-content #logo-wheel').length) {
    normalWidth = 132;
    preWidth = 153;
    currentWidth = 182;
  } else {
    normalWidth = 182;
    preWidth = 205;
    currentWidth = 228;
  }
  switch (clicked) {
    case 'next':
    default:
      $('#logo-wheel ul').animate({'left':'-='+liWidth}, 400);
      preEl.children('img').animate({'width':normalWidth, 'margin-top':12}, 200);
      preEl.animate({'margin-left':0, 'margin-right':0}, 200, function() {
        $(this).removeClass('pre');
      })
      currentEl.children('img').animate({'width':preWidth, 'margin-top':6}, 200);
      currentEl.animate({'margin-left':-72, 'margin-right':0}, 200, function() {
        $(this).removeClass('current').addClass('pre');
      })
      postEl.children('img').animate({'width':currentWidth, 'margin-top':0}, 200);
      postEl.animate({'margin-left':-54, 'margin-right':-54}, 200, function() {
        $(this).removeClass('post').addClass('current');
      })
      nextEl.children('img').animate({'width':preWidth, 'margin-top':6}, 200);
      nextEl.animate({'margin-left':0, 'margin-right':-72}, 200, function() {
        $(this).addClass('post');
      })
      break;
    case 'back':
      $('#logo-wheel ul').animate({'left':'+='+liWidth}, 400);
      prevEl.children('img').animate({'width':preWidth, 'margin-top':6}, 200);
      prevEl.animate({'margin-left':-72, 'margin-right':0}, 200, function() {
        $(this).addClass('pre');
      })
      preEl.children('img').animate({'width':currentWidth, 'margin-top':0}, 200);
      preEl.animate({'margin-left':-54, 'margin-right':-54}, 200, function() {
        $(this).removeClass('pre').addClass('current');
      })
      currentEl.children('img').animate({'width':preWidth, 'margin-top':6}, 200);
      currentEl.animate({'margin-left':0, 'margin-right':-72}, 200, function() {
        $(this).removeClass('current').addClass('post');
      })
      postEl.children('img').animate({'width':normalWidth, 'margin-top':12}, 200);
      postEl.animate({'margin-left':0, 'margin-right':0}, 200, function() {
        $(this).removeClass('post');
      })
      break;
  }
}


function resetBanner(onComplete) {
  var windowWidth = $(window).width(),
    bannerLeft = $('.site-width').offset().left,
    itemSpan = 540;
  $('#banner .figure').css('left', windowWidth-bannerLeft);
  $('#banner .quote').css('left', 0-bannerLeft-itemSpan);
  $('#banner .name').css('left', 0-bannerLeft-itemSpan);
  $('#banner .logo').css('left', 0-bannerLeft-itemSpan);
  if (onComplete) { onComplete(); }
}

function moveBannerIn(onComplete) {
  var figureWidth = 480;// $('#banner').width()-$('#banner .figure').width();
  $('#banner .current .quote').delay(400).animate({'left':28}, 400);
  $('#banner .current .figure').delay(800).animate({'left':figureWidth}, 400);
  $('#banner .current .name').delay(960).animate({'left':28}, 400);
  $('#banner .current .logo').delay(1040).animate({'left':28}, 400, function() {
    readyState = 'onScreen';                               
    if (onComplete) { onComplete(); }
  });
}

function moveBannerOut(onComplete) {
  var windowWidth = $(window).width(),
    bannerLeft = $('.site-width').offset().left,
    itemSpan = 540;
  $('#banner .current .quote').delay(400).animate({'left':0-bannerLeft-itemSpan}, 400);
  $('#banner .current .figure').delay(800).animate({'left':windowWidth-bannerLeft}, 400);
  $('#banner .current .name').delay(960).animate({'left':0-bannerLeft-itemSpan}, 400);
  $('#banner .current .logo').delay(1040).animate({'left':0-bannerLeft-itemSpan}, 400, function() {
    if (onComplete) { onComplete(); }
  });
}

function switchBanners() {
  moveBannerOut(function() {
    if($('#banner .current').next('div').length) {
        nextBanner = $('#banner .current').next('div');
    } else {
  nextBanner = $('#banner div:first-child');
    }
    $('#banner').removeClass().addClass(nextBanner.attr('id'));
    $('#banner').find('.current').removeClass('current');
    nextBanner.addClass('current');
    //Switch banner images
    //var oldBanner = banners[currentBanner++];
    //if (!banners[currentBanner]) {
    //  currentBanner = 0;
    //}
    //newBanner = banners[currentBanner];
    //
    //$('#banner').removeClass().addClass(newBanner);
    //var quoteSrc = $('#banner .quote').attr('src').replace(oldBanner, newBanner),
    //  figureSrc = $('#banner .figure').attr('src').replace(oldBanner, newBanner),
    //  nameSrc = $('#banner .name').attr('src').replace(oldBanner, newBanner),
    //  logoSrc = $('#banner .logo').attr('src').replace(oldBanner, newBanner);
    //$('#banner .quote').attr('src', quoteSrc);
    //$('#banner .figure').attr('src', figureSrc);
    //$('#banner .name').attr('src', nameSrc);
    //$('#banner .logo').attr('src', logoSrc);
    moveBannerIn();
  });
}
