/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
  /**
   * Function takes a jquery object and a css property (called dimension) and determines how many pixels the item is
   * @param {jQuery Object} $item The jQuery object we're looking at
   * @param {String} dimension The CSS property name to look for
   * @returns The width or height of the CSS property with 'px' removed
   * @type Number
   */
  var determineDimension = function($item, dimension) {
    $item = $($item);
    if ($item.css(dimension)) {
      return parseInt($item.css(dimension).replace('px', ''), 10);
    } else {
      return 0;
    };
    return false;
  };

  var resizeImage = function($image, $parent, $container) {
    // Determine the width of the image along with borders and padding
    var imageWidth = $image.width();
    var paddingLeft = determineDimension($image, 'padding-left');
    var paddingRight = determineDimension($image, 'padding-right');
    var borderLeft = determineDimension($image, 'border-left-width');
    var borderRight = determineDimension($image, 'border-right-width');

    // Calculate total edge (padding and border) width and the total width (edge and image)
    var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
    var totalWidth = imageWidth + edgeWidth;

    // Determine parent width
    var parentWidth = $parent.width();

    // If the image is greater then the threshold times the parent width resize the image and the container width
    // Otherwise set the image left's div to the size of the image plus the edge
    if ((threshold * parentWidth) <= totalWidth) {
      var revisedWidth = parentWidth * threshold;
      var revisedImageWidth = revisedWidth - edgeWidth;

      $image.width(revisedImageWidth);
      $container.width(parseInt(revisedWidth, 10));
    } else {
      $container.width(totalWidth);
    };
  };

  return this.each(function() {
    // Threshold is the maximum width an image plus its border and padding can be 
    // in relation to its parent container
    var threshold = (threshold) ? threshold : 2/3;

    // Find image within div
    var $image = $('img', $(this));
    var $parent = $(this).parent();
    var $container = $(this);

    $image.each(function(index) {
      resizeImage($image, $parent, $container);
      $(this).load(function() {     
        resizeImage($image, $parent, $container);
      });
    });
  });   
};

/**
 * Builds pull quote divs assuming you've wrappted your content with a span with the class: pullquote-left or pullquote-right
 */
$.fn.pullQuote = function() {
  return this.each(function() {
    var contents = $.trim($(this).html());
    var firstCharacterCode = contents.charCodeAt(0);
    if (firstCharacterCode < 65 || firstCharacterCode > 96) {
      contents = '&hellip; ' + contents;
    };
    
    var lastCharacter = contents.charAt(contents.length - 1);
    if ("?!.".search(lastCharacter) < 0) {
      contents = contents + ' &hellip;';
    };
    var $parent = $(this).parent();
    var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
    $parent.before($pullquote);
  });   
};

/**
 * Clears a text form element when it has the style 'clear-default'
 */
$.fn.clickClear = function() {
  return this.each(function() {
    this.defaultValue = $(this).val();
    $(this).click(function() {
      if ($(this).val() == this.defaultValue) {
        $(this).val('');
      };
    }).focus(function() {
      if ($(this).val() == this.defaultValue) {
        $(this).val('');
      };
    }).blur(function() {
      if ($(this).val() == "") {
        $(this).val(this.defaultValue);
      };
    });
    
    $('form').submit(function(event) {
      if ($(this).val() == this.defaultValue) {
        $(this).val('');
      };
    });
  }); 
};

/**
 * Clears a textarea element when it has the style 'clear-default'
 */
$.fn.clickClearTA = function() {
  return this.each(function() {
    this.defaultValue = $(this).html();
    $(this).click(function() {
      if ($(this).html() == this.defaultValue) {
        $(this).html('');
      };
    }).focus(function() {
      if ($(this).html() == this.defaultValue) {
        $(this).html('');
      };
    }).blur(function() {
      if ($(this).html() == "") {
        $(this).html(this.defaultValue);
      };
    });
    
    $('form').submit(function(event) {
      if ($(this).html() == this.defaultValue) {
        $(this).html('');
      };
    });
  }); 
};

var markupPrep = function() {
  var listPrep = function() {
    $('ul li:last, ol li:last, ul#comments li:last, ul.related li:last').addClass('last');
  };
  
  var tablePrep = function() {
    $('table tr:odd').addClass('alt');
    $('table td:last, table th:last').addClass('last');
  };
  
  listPrep();
  tablePrep();
};

var imageTitlePopup = function(){ 
  $(".archive #content-section ul.images li a").mouseover(function(){
    var title = this.title;
    var top = $(this).position().top;
    var left = $(this).position().left;
    var topOffset = 44;
    var leftOffset = 30;
    
    $(".archive #content-section").append("<div class='tooltip'><p>"+ title +"</p></div>");                
    $("div.tooltip")
      .css("top",(top - topOffset - $('div.tooltip').height()) + "px")
      .css("left",(left - leftOffset) + "px");          
    }).mouseout(function() {
    $("div.tooltip").remove();
    }); 

};

function carousel(image) {
  switch (image) {
    case 1:
      $('div.one').animate({opacity:1},1000);
      $('div.two').animate({opacity:0},1000);
      $('div.three').animate({opacity:0},1000);
      $('div.four').animate({opacity:0},1000);
      $('ul#nav').children().removeClass('selected');
      $('ul#nav li.nav1').addClass('selected');
      link = $('div.one a').attr('href');
      $('ul#nav li#arrow a').attr('href', link);
      break;
    case 2:
      $('div.two').animate({opacity:1},1000);
      $('div.one').animate({opacity:0},1000);
      $('div.three').animate({opacity:0},1000);
      $('div.four').animate({opacity:0},1000);
      $('ul#nav').children().removeClass('selected');
      $('ul#nav li.nav2').addClass('selected');
      link = $('div.two a').attr('href');
      $('ul#nav li#arrow a').attr('href', link);
      break;
    case 3:
      $('div.three').animate({opacity:1},1000);
      $('div.two').animate({opacity:0},1000);
      $('div.one').animate({opacity:0},1000);
      $('div.four').animate({opacity:0},1000);
      $('ul#nav').children().removeClass('selected');
      $('ul#nav li.nav3').addClass('selected');
      link = $('div.three a').attr('href');
      $('ul#nav li#arrow a').attr('href', link);
      break;
    case 4:
      $('div.four').animate({opacity:1},1000);
      $('div.two').animate({opacity:0},1000);
      $('div.three').animate({opacity:0},1000);
      $('div.one').animate({opacity:0},1000);
      $('ul#nav').children().removeClass('selected');
      $('ul#nav li.nav4').addClass('selected');
      link = $('div.four a').attr('href');
      $('ul#nav li#arrow a').attr('href', link);
      break;
    default:
      break;
  }
}

function homePage () {
  if ($('body#home').size() > 0) {
    $('ul.inside-nc li a').lightBox();
  
    $('#carousel-items').innerFade({
      speed: 'slow',
      timeout: 10000,
      indexContainer: '#carousel ul#nav'
    });
  };
}

/**
 * Load the larger biography on the individual team pages
 */
function moreAboutMe () {
  if ($('#team .bio').size() > 0) {
    $('.bio a').click(function(event) {
      event.preventDefault();
      $('.info-panel').toggle('fast');
    });
  };
}

function portfolio() {
  if ($('body.portfolio-detail').size() > 0) {
    $('.portfolio-detail #content-section ul.images li a').lightBox({
      fixedNavigation:false
    });
  };
}

function partners () {
  if ($('#partners').size() > 0) {
    $('#like-minded-companies h3 a').click(function(event) {
      event.preventDefault();
      var $hiddenBlock = $('#like-minded-companies > div:hidden');
      $('#like-minded-companies > div:visible').slideUp('normal', function() {
        $hiddenBlock.slideDown('normal');
      });
    });
  };
}

function lightbox() {
  if ($('a[rel*=lightbox]').size()) {
    $('a[rel*=lightbox]').lightBox();
  };
}

$(document).ready(function() {
  $('input.clear-default').clickClear();
  $('textarea.clear-default').clickClearTA();
  $('div.image-left, div.image-right').imageWidth();
  $('span.pullquote-left, span.pullquote-right').pullQuote();
  imageTitlePopup();
  markupPrep();
  
  lightbox();
  homePage();
  moreAboutMe();
  portfolio();
  partners();
  
  var agent = navigator.userAgent.toLowerCase();
  var is_iphone = (agent.indexOf('iphone') != -1);
  if (is_iphone) {
    if ($('#content-section:has(> *:visible)').size() == 0) {
      $('#content-section').hide();
    }
  }
});
