// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

// remap jQuery to $
(function ($) {
  
  

  if ($('#case-study-list').length) {
    setup_channel_viewer();
  }

  if ($('.channels').length) {
    $(".channels li").tooltip({
      track: true,
	    delay: 0,
	    showURL: false,
	    fade: 250,
      top:30,
      left: -20,
      extraClass: "right",
      bodyHandler: function () {
        return $(this).html();
      }
    });
  }
  
  if($(".video-link").length){
    $('.video-link').colorbox({width:"634px", innerHeight:"361px", inline:true, href:"#video-wrapper"});
    call_telegraph();
  }
  
  if($(".showreel-link").length){
    $('.showreel-link').colorbox({width:"634px", innerHeight:"361px", inline:true, href:"#video-wrapper"});
    call_showreel();
  }
  
  if($(".millionextra-vid").length){
    $('.millionextra-vid').colorbox({width:"634px", innerHeight:"361px", inline:true, href:"#video-wrapper"});
    call_millionextra();
  }
  
  if($("#people-list").length) {
    
    //assign colorbox to faces
    $('.person-modal').colorbox({inline:true, width:"780px"}); 
    
    //create array of selectors for navigation
    panes = $('.people-list-pane').length;
    navigation_array = new Array();
    for(i=0; i < panes; i++) {
      navigation_array[i] = '#people-navigation .pane-'+(i+1);
    }
    
    $('#people-navigation li a').click(function() {
      $('#people-navigation li a').removeClass('current');
      $(this).addClass('current');
    });
    
    $('#people-list').jCarouselLite({
      btnGo: navigation_array,
      speed: 750,
      visible: 1
    });
  }
  
  
  
  function call_showreel(){
   var flashvars = {};
		//file path relative to swf
		flashvars.video_src = '../videos/waa_showreel.mp4';
		flashvars.image_src = 'null';
		flashvars.controls_above = 'true';
		flashvars.restart_btn = 'off';
		flashvars.time_display = 'off';
		flashvars.volume_controls = 'on';
		flashvars.full_screen = 'on';
		var params = {};
		params.allowfullscreen = "true";
		swfobject.embedSWF("/flash/MediaPlayer.swf", "video", "634", "357", "9.0.115", "/flash/expressInstall.swf",flashvars,params);
  }
  
  function call_telegraph(){
   var flashvars = {};
		//file path relative to swf
		flashvars.video_src = '../videos/waa_telegraph.mp4';
		flashvars.image_src = 'null';
		flashvars.controls_above = 'true';
		flashvars.restart_btn = 'off';
		flashvars.time_display = 'off';
		flashvars.volume_controls = 'on';
		flashvars.full_screen = 'on';
		var params = {};
		params.allowfullscreen = "true";
		swfobject.embedSWF("/flash/MediaPlayer.swf", "video", "634", "357", "9.0.115", "/flash/expressInstall.swf",flashvars,params);
  }
  
  function call_millionextra(){
   var flashvars = {};
		//file path relative to swf
		flashvars.video_src = '../videos/waa_millionextra.mp4';
		flashvars.image_src = 'null';
		flashvars.controls_above = 'true';
		flashvars.restart_btn = 'off';
		flashvars.time_display = 'off';
		flashvars.volume_controls = 'on';
		flashvars.full_screen = 'on';
		var params = {};
		params.allowfullscreen = "true";
		swfobject.embedSWF("/flash/MediaPlayer.swf", "video", "634", "357", "9.0.115", "/flash/expressInstall.swf",flashvars,params);
  }
  
  
  
  function sync_navigation() {
    if($('#about-us-header').hasClass('closed')) {
      $('#about-us-header').switchClass('closed', 'open', 0);
      current_nav = $('#selected');
      current_nav.removeAttr('id');
      $('#about-us-nav').parent().attr('id', 'selected');
      if(!$('#about-us-header .row').length){
        $('#about-us-header').load('/about-us-ajax', function() {
          $('#about-us-header .row').fadeIn('slow');
          $('#about-us-header .formatting a:not(#about-close)').click(function() {
             var pos = $(this).attr("rel");
             $('#about-us-header .img').stop().animate({
               backgroundPosition: pos
             }, 1000, "easeInOutCubic");
             return false; 
          });
        });
      }
      
    } else {
      $('#about-us-header').switchClass('open', 'closed', 0);
      $('#about-us-nav').parent().removeAttr('id');
      current_nav.attr('id', 'selected');
    }
  }
  
  $('#about-us-nav, #about-close').live('click', function() {
    if(!$('#about-us-header').length){
      $("body").prepend('<div id="about-us-header" class="closed"><span id="loading">Loading</span></div>');
    }
    $('#about-us-header').slideToggle('slow', 'easeInOutCubic', sync_navigation);
    return false;
  });

  
  
  // if($('#birmingham-map').length && $('#london-map').length) {
  if($('#birmingham-map').length) {
    setup_maps();
  }

  // Init Gallery functionality
  $(window).load(function(){
    if ($(".gallery").length) {
      ftnInitGallery();
    }
  });
  
  if($('#flickr-gallery').length) {
    setup_flickr_gallery();
  }
  
  if($('#cm-form').length) {
    newsletter_form_validation();
  }

  // Open new window for external links
  $('A[rel="external"]').click(function () {
    window.open($(this).attr('href'));
    return false;
  });

})(this.jQuery);

  var channel_menu_current = 'all';
  var channel_all_name = "all";

/*
*****************
Set up case study channel selector
*****************
*/
function setup_channel_viewer() {
  setup_initial_state();
  setup_channel_menu();
}

/*
*****************
Set up channel selector and view in intial closed state.
*****************
*/
function setup_initial_state() {
  
  channel_menu_current = 'all';
  channel_all_name = 'all';
  gridItemCoords = new Array(); //Place grid item coordinations into array
  
  prefiltered = parse_initial_url();
  
    $('#selector-toggle').bind('click', function() {
      if($(this).hasClass('open')) {
        toggle_channel_filter(false);
      } else {
        toggle_channel_filter(true);
      }
    });
    
    if(!prefiltered) {
    if($('#selector-toggle').hasClass('open')) {
      $('#selector-toggle').addClass('closed').removeClass('open');
      $('#channels-container ul').hide();
    }
  }

}

/*
*****************
Toggle case study channel selector
state - true = to open
state - false = to close
*****************
*/
function toggle_channel_filter(state) {
  if(state) {
    $('#selector-toggle').switchClass('closed', 'open', 0);
    $('#channels-container ul').slideToggle('slow', 'easeInOutCubic');
  } else {
    $('#selector-toggle').switchClass('open', 'closed', 0);
    $('#channels-container ul').slideToggle('slow', 'easeInOutCubic');
  }
}

/*
*****************
Setup channel menu.
*****************
*/
function setup_channel_menu () {
  $("#channels-container li").each(function() {
    // var hash = $("a", this).attr('href'); 
    //     current_item = hash.substr(hash.indexOf("#")+1);    
    $("a", this).bind("click", function() {  
      var hash = $(this).attr('href'); 
      current_item = hash.substr(hash.indexOf("#")+1);
      if(current_item != channel_menu_current) {
        sortGridItems(current_item);
        $("#channels-container li").removeClass("selected");
        $(this).parent().addClass("selected");
      }
      //dont return false or the URL isn't updated meaning state isn't kept on refresh.
      return false;
    });
    
  });
  
  var itemWidth = 332; //Width+margin
  var itemHeight = 350; //Height+margin
  var itemBottomMargin = 30;
  var itemsPerRow = 3;
  var itemXCoord = 0;
  var itemYCoord = 0;
  var itemCount = 0;
  var gridHeight = 350;
  
  $("#case-studies li").each(function() {
    gridItemCoords[itemCount] = itemXCoord + "-" + itemYCoord;
    $(this).css({
      "position": "absolute",
      "top": itemYCoord+"px",
      "left": itemXCoord+"px"
    });
    itemXCoord += itemWidth;
    if(itemXCoord > (itemWidth*(itemsPerRow-1))) {
      itemXCoord = 0;
      itemYCoord += itemHeight;
      gridHeight += itemHeight;
    }
    $(this).attr("location", itemCount);
    itemCount++;
  });
  
  if(is_int((itemCount/itemsPerRow))) {
    gridHeight -= itemHeight;
  }
  $("#case-studies").css({ "height": (gridHeight-itemBottomMargin)+"px" });
  
}

function sortGridItems(sortValue) {
  
  var newItemPos = 0;
  
  $("#case-studies").animate({
    "margin-left": 0 //Ensure movement animation doesn't start until fade is complete
  }, 400, function() {
    
    
    $("#case-studies li").each(function() {
      $(this).animate({
        opacity: 0.1
      }, 400);
    }).each(function() {
      //Bring all items to 0,0 before spraying out to new home
      $(this).animate({
        top: "0px",
        left: "0px"
      }, 500);
    }).each(function() {
      if($(this).hasClass(sortValue)) {
        var itemXCoord = gridItemCoords[newItemPos].substr(0, gridItemCoords[newItemPos].indexOf("-"));
        var itemYCoord = gridItemCoords[newItemPos].substr(gridItemCoords[newItemPos].indexOf("-")+1);
        $(this).animate({
          top: itemYCoord+"px",
          left: itemXCoord+"px"
        }, 900);
        newItemPos++;
      }
    }).each(function() {
      if(!$(this).hasClass(sortValue)) {
        var itemXCoord = gridItemCoords[newItemPos].substr(0, gridItemCoords[newItemPos].indexOf("-"));
        var itemYCoord = gridItemCoords[newItemPos].substr(gridItemCoords[newItemPos].indexOf("-")+1);
        $(this).animate({
          top: itemYCoord+"px",
          left: itemXCoord+"px"
        }, 900);
        newItemPos++;
      }
    }).each(function() {
      if($(this).hasClass(sortValue) || sortValue == channel_all_name) {
        $(this).animate({
          opacity: 1
        }, 400);
      } else {
        $(this).animate({
          opacity: 0.1
        }, 400);
      }
    });
    
  });
  channel_menu_current = sortValue;
  
}

/*
*****************
Parse URL and preset channel selector is #<value> is present
return BOOL
*****************
*/
function parse_initial_url() {
  var current_url = document.URL;
  if(current_url.indexOf("#")==-1) {
    return false;
  } else {
    current_url = current_url.substr(current_url.indexOf("#")+1);
    if(current_url != null && current_url != "") {
      current_url = current_url.toLowerCase();
      sortGridItems(current_url);
      $("#channels-container li").removeClass("selected");
      $("#channels-container li a").each(function() {
        if($(this).attr("href")=="#"+current_url) {
          $(this).parent().addClass("selected");
          channel_menu_current = current_url;
          preset = true;
        }
      });
      if(preset) {
        return true;
      }
    }
    return false;
  }
}

/*
*****************
Check value is actually an integer
return BOOL
*****************
*/
function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
    return true;
  } else {
    return false;
  }
}

/*
*****************
Set up Google Maps
*****************
*/
function setup_maps() {
  birmingham_map();
  london_map();
}

function birmingham_map() {
  var myLatlng = new google.maps.LatLng(52.561684, -1.821070);
  var myOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("birmingham-map"), myOptions);
  
  var contentString = '<div class="infowindow-content"><p><strong>WAA</strong><br />Wrens Court,<br />58 Victoria Road,<br />Sutton Coldfield,<br />West Midlands,<br />B72 1SY.</p></div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString,
      maxWidth: 200
  });
  
  var marker = new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    position: myLatlng, 
    map: map,
    title:"WAA - Birmingham"
  });
  
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

function london_map() {
  var myLatlng = new google.maps.LatLng(52.561684, -1.821070);
  var myOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("london-map"), myOptions);
  
  var contentString = '<div class="infowindow-content"><p><strong>WAA</strong><br />Wrens Court,<br />58 Victoria Road,<br />Sutton Coldfield,<br />West Midlands,<br />B72 1SY.</p></div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString,
      maxWidth: 200
  });
  
  var marker = new google.maps.Marker({
    animation: google.maps.Animation.DROP,
    position: myLatlng, 
    map: map,
    title:"WAA - London"
  });
  
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

/*
*******************
Gallery functionality
********************
*/

function ftnInitGallery() {
  $(".gallery").each(function (index) {
    //default settings
    
    var nextText = "Next Image"
    var previousText = "Previous Image"

    var topZindex = $("li", this).length;
    var curZindex = 0;
    var galleryListItem = $("li", this);
    var galleryHeight = $(this).find("li:first").height();
    var galleryMargin = $(this).css("margin-bottom");
    var curImg = 0;
    
    if($(this).hasClass("sml-btns")){
      var smallBtns = true;
    }
    
    if($(this).hasClass("no-counter")){
      var noCounter = true;
    }
    
    if($(this).hasClass("auto")){
      var auto = true;
      var galleryTimeOut;
    }
    
    
    $(this).css("margin-bottom",0).wrap("<div class='gallery-wrapper'/>").parent(".gallery-wrapper").height(galleryHeight)
                                                                                                    .css("margin-bottom", galleryMargin)
                                                                                                    .append("<a class='next ir png_bg' href='next'><span>" + nextText + "</span></a>")
                                                                                                    .append("<a class='previous ir png_bg' href='previous'><span>" + previousText + "</span></a>");
                                                                                                
    var galleryWrapper = $(this).parent(".gallery-wrapper");
    galleryWrapper.data('active',true);
    
    if(!noCounter){
      galleryWrapper.append("<span class='img-counter png_bg' style='display:none;'> 1 of " + topZindex + " </span>");
    }
    
    var galleryImgCounter = galleryWrapper.find(".img-counter");
    if(!smallBtns){
      galleryWrapper.find(".next, .previous").height(galleryHeight);
    } else {
      galleryWrapper.addClass("gallery-wrapper-sml-btns");
    }
    

    if (topZindex > 1) { // if more than 1 image
      galleryListItem.css("z-index", topZindex).each(function (counter) {
        curZindex = topZindex - counter // total number of imgs - counter
        $(this).css("z-index", curZindex); // sets z-index
        
        if (counter >= 1) {
          $(this).hide(); // hides all list items apart from first
        }
      })
    }

    galleryWrapper.find(".next").click(function () {
      ftnNextImg();
      if(auto){
        clearTimeout(galleryTimeOut);
        ftnSetTimeout();
      }
      return false;
    });

    galleryWrapper.find(".previous").click(function () { // click
      ftnPrevImg();
      if(auto){
        clearTimeout(galleryTimeOut);
        ftnSetTimeout();
      }
      return false;
    });
    
    if(!noCounter){
      galleryWrapper.hover(
        function () {
          galleryImgCounter.fadeIn("fast");
        },
        function () {
          galleryImgCounter.fadeOut("fast");
        }
      )
    }
    
    if(auto){
      ftnSetTimeout();
    }
    
    function ftnNextImg(){
      if( galleryWrapper.data('active') ){
        galleryWrapper.data('active',false);
        galleryListItem.each(function (i) { // Loops through list items
          var myZIndex = Number($(this).css("z-index")) + 1; // adds 1 to all list item z-index
          $(this).css("z-index", myZIndex);

          if (topZindex === myZIndex) { // shows next list item in line
            $(this).show();
          }
        });
        galleryListItem.eq(curImg).fadeOut(500, function () { // Fades out top list item
          $(this).css("z-index", "1"); // sets z-index to bottom
          galleryWrapper.data('active',true);
        });

        curImg = ((curImg + 1) < topZindex) ? ++curImg : 0;
        if(!noCounter){
          galleryImgCounter.text((curImg + 1) + " of " + topZindex);
        }
      }
    }

    function ftnPrevImg(){
      if( galleryWrapper.data('active') ){
        galleryWrapper.data('active',false);
        galleryListItem.each(function (i) { // Loops through list items
          var myZIndex = Number($(this).css("z-index")) - 1; // minus 1 to all list item z-index
          $(this).css("z-index", myZIndex);
          if (myZIndex === 0) { // shows next list item in line
            $(this).fadeIn(500, function () { // Fades in
              $(this).siblings().hide(); // hides others after fade
              galleryWrapper.data('active',true);
            }).css("z-index", topZindex); // Sets highest z-index
          }
        });
        curImg = ((curImg - 1) >= 0) ? --curImg : topZindex - 1;
        if(!noCounter){
          galleryImgCounter.text((curImg + 1) + " of " + topZindex);
        }
      }
    }
    
    function ftnSetTimeout(){
      galleryTimeOut = setTimeout(ftnShowNextImage, 10000);
    }

    function ftnShowNextImage() {
      ftnNextImg();
      ftnSetTimeout();
    }

  });
}

/*
*******************
Flickr Gallery functionality
********************
*/
function setup_flickr_gallery() {
  $('#flickr-gallery').jflickrfeed({
  	limit: 10,
  	qstrings: {
  		id: '25456980@N05'
  	},
    // itemTemplate: '<li><a href="{{image}}" rel="external"><img src="{{image_m}}" alt="{{title}}" /></a></li>'
    itemTemplate: '<li><img src="{{image_m}}" alt="{{title}}" /></li>'
  }, function(data) {
  	$('#flickr-gallery div').hide();
  	$('#flickr-gallery').cycle({
  		timeout: 5000
  	});
  	$('#flickr-gallery li').hover(function(){
  		$(this).children('div').show();
  	},function(){
  		$(this).children('div').hide();
  	});
  });
}

/*
*******************
newsletter_form_validation
********************
*/
function newsletter_form_validation() {
  $('#cm-form').submit(function() {
    var email_regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-z0-9-]+)*(\.[a-zA-Z]{2,4})$/i; 
    var email_address_field = $('#ajlddj-ajlddj');
    var error_msg = $('#error_msg');
    
    if(!email_regex.test(email_address_field.val())) {
      email_address_field.addClass('error_field');
      error_msg.removeClass('hidden');
      return false;
    }
    
  });
}


// catch all document.write() calls
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);
