var Showcase = function() {

  /***************
  PUBLIC FUNCTIONS
  ***************/
  var next = function() {
    var slide_distance = ( jQuery.browser.msie ? $(window).width() : 400 )
    var showcase = $('#Showcase')
    
    showcase.addClass('transitioning').find('.active').animate({
      left: slide_distance,
      opacity: 0
    }, {
      easing: 'easeOutQuint',
      complete: function() {
        showcase.removeClass('transitioning')
        $(this).removeClass('active').css({
          left: 0,
          opacity: 1
        }).find('.caption').css('opacity', 0).hide()
        this.style.filter = 'none'
        if($(this).next().size()) start_animation($(this).next())
        else start_animation($('#Showcase .section:first'))
      }
    })
  }


  /***************
  PRIVATE FUNCTIONS
  ***************/
  var setup = function() {
    if($('#Showcase').size() == 0) return
    
    jQuery.each(jQuery.browser, function(browser, value) {
      if(value == true) $('body').addClass(browser)
    })
    
    setTimeout(function() {
      start_animation($('#Showcase .section:first'))
    }, 600)
  }
  $(window).load(setup)

  
  var start_animation = function(slide) {
    start_text_animation(slide.find('.text'))

    var image_1 = slide.find('.image.first').hide()
    var image_2 = slide.find('.image.second').hide()
    preload_image(image_1, function() {
      start_image_animation(image_1)
      preload_image(image_2, start_image_animation)
    })

    slide.addClass('active')
  }


  var preload_image = function(image_wrapper, callback) {
    image_wrapper = $(image_wrapper)
    var image_cropper = image_wrapper.find('.cropper')
    
    var image_path = image_cropper.css('background-image').replace('url(', '').replace(')', '').replace(/\"/g, '')
    var tmp_image = new Image()
    tmp_image.onload = function() {
      image_cropper.data('width', tmp_image.width)
      image_cropper.data('height', tmp_image.height)
      image_cropper.data('backgroundPositionX', parseInt(image_cropper.css('backgroundPosition').split(' ')[0]))
      image_cropper.data('backgroundPositionY', parseInt(image_cropper.css('backgroundPosition').split(' ')[1]))

      if(tmp_image.width != 210 || tmp_image.height != 157) {
        image_cropper.mouseenter(expand_image)
        image_cropper.mouseleave(contract_image)
      }
      setTimeout(function() { callback(image_wrapper) }, 0) // For IE
    }
    tmp_image.src = image_path
  }
  
  
  var start_image_animation = function(image_wrapper) {
    image_wrapper = $(image_wrapper)

    if($('#Showcase .active .animating').size()) {
      image_wrapper.addClass('waiting')
    }
    else {
      var image_cropper = image_wrapper.show().find('.cropper')
      image_wrapper.removeClass('waiting').addClass('animating')
      
      var starting_offset_x = image_cropper.data('backgroundPositionX')
      var starting_offset_y = image_cropper.data('backgroundPositionY')      
      
      image_cropper.css({
        width: image_cropper.data('width'),
        height: image_cropper.data('height'),
        marginLeft: starting_offset_x - 100,
        marginTop: starting_offset_y,
        backgroundPosition: '0 0',
        opacity: 0
      }).animate({
        opacity: 1,
        marginLeft: starting_offset_x
      }, {
        duration: 1000, 
        easing: 'easeOutQuint',
        complete: function() {
          image_wrapper.removeClass('animating')
          check_for_waiting_images()
        }
      }).animate({
        width: 210,
        height: 157,
        marginLeft: 0,
        marginTop: 0,
        backgroundPosition: '(' + starting_offset_x + 'px ' + starting_offset_y + 'px)'
      }, {
        duration: 300,
        easing: 'linear'
      })
    }
    
  }


  var check_for_waiting_images = function() {
    var waiting = $('.waiting')
    if(waiting.size())
      waiting.each(function() { start_image_animation(this) })
    else
      $('#Showcase .next:hidden, #Showcase .active .caption').css('opacity', 0).show().stop().fadeTo(600, 1)
  }


  var start_text_animation = function(text_block) {
    text_block.addClass('animating').find('h2, p, blockquote').css({
      opacity: 0,
      left: -100
    }).each(function(i) {
      this.style.filter = 'alpha(opacity=0)'
      $(this).delay(i * 300).animate({
        opacity: 1,
        left: 0
      }, {
        duration: 1400, 
        easing: 'easeOutQuint',
        complete: function() { this.style.filter = 'none' }
      })
    })
    
    setTimeout(function() {
      var showcase = $('#Showcase')
      var slide = text_block.parent()
      if(text_block.height() + 40 > showcase.height() || showcase.height() != 222){
        var new_height = Math.max(text_block.height() + 40, 222)
        showcase.animate({height: new_height})
      }
    }, 400)
    
    setTimeout(function() {
      text_block.removeClass('animating')
      check_for_waiting_images()
    }, 1400)
  }


  var expand_image = function() {
    if($('#Showcase .active .animating').size()) return
    image_cropper = $(this)
    image_cropper.parent().css('zIndex', 5)

    image_cropper.stop().animate({
      width: image_cropper.data('width'),
      height: image_cropper.data('height'),
      marginLeft: image_cropper.data('backgroundPositionX'),
      marginTop: image_cropper.data('backgroundPositionY'),
      backgroundPosition: '(0 0)'
    }, {
      duration: 300,
      easing: 'linear'
    })
  }


  var contract_image = function() {
    if($('#Showcase .active .animating').size()) return
    image_cropper = $(this)
    image_cropper.parent().css('zIndex', 4)
    
    image_cropper.stop().animate({
      width: 210,
      height: 157,
      marginLeft: 0,
      marginTop: 0,
      backgroundPosition: '(' + image_cropper.data('backgroundPositionX') + 'px ' + image_cropper.data('backgroundPositionY') + 'px)'
    }, {
      duration: 300,
      easing: 'linear'
    })
  }


  return {
    next: next,
    expand_image: expand_image,
    contract_image: contract_image
  }
  
}()


var Content = function() {

  _active_color = 'rgb(255, 255, 255)'
  _inactive_color = 'rgb(0, 63, 66)'

  /***************
  PUBLIC FUNCTIONS
  ***************/
  var show = function(nav_el, content_id) {
    $('#Main .active').removeClass('active').find('a').find('img').css('backgroundColor', _inactive_color)
    $(nav_el).parent().addClass('active').find('a').find('img').css('backgroundColor', _active_color)
    $('#' + content_id).addClass('active')    
  }


  /***************
  PRIVATE FUNCTIONS
  ***************/
  var setup = function() {
    $('#Main .nav li').bind('mouseover mouseout', fade_link_color)
    if(window.location.hash.indexOf('Show') != -1)
      $(window.location.hash.replace('Show', '')+'Link a').click()
  }
  $(document).ready(setup)


  var fade_link_color = function(e) {
    if($(this).hasClass('active')) return
    var fade_color = ( e.type == 'mouseover' ? _active_color : _inactive_color )
    var image = $(this).find('img')
    if(image.is(':animated')) image.stop()
    image.animate({backgroundColor: fade_color}, {duration: 'fast'})
  }


  return {
    show: show
  }

}()


var ContactForm = function() {
  
  var _captcha = {};
  var _header
  var _contact_form
  
  var setup = function() {
    _header = $('.header')
    _header_starting_height = _header.height()
    _contact_form = $('#ContactForm')
    
    if($('#ContactForm').size() == 0) return
    _captcha = new InvisibleCaptcha('#ContactForm')
  }
  $(document).ready(setup)
  
  
  var show_message = function(message, className) {
    if(!message) {
      $('#ContactMessage').hide()
    }
    else {
      $('#ContactMessage').removeClass()
      if(className) $('#ContactMessage').addClass(className)
      $('#ContactMessage').html(message)
      $('#ContactMessage').show()
      show()
    }
    
  }
  
  
  var show = function() {
    if(_contact_form.hasClass('contactJustSent')) {
      _contact_form.removeClass('contactJustSent')[0].reset()
      $('#ContactMessage').hide()
    }
    _contact_form.show()
    _header.addClass('showing').stop().animate({
      height: _header_starting_height + _contact_form.innerHeight() + 18
    }, {
      duration: 500
    })
  }


  var hide = function() {
    _header.removeClass('showing').stop().animate({
      height: _header_starting_height
    }, {
      duration: 500,
      complete: function() {
        _contact_form.hide()
      }
    })
  }
  

  /***************
  PUBLIC FUNCTIONS
  ***************/
  var toggle = function() {
    $('.header').hasClass('showing') ? hide() : show()
  }


  var submit = function() {
    show_message(false)
    
    if(!_captcha.verify()) {
      return show_message('Please fill in the form before submitting.', 'error')
    }
    
    var contact = {
      'Name':     $.trim($('#ContactName').val()),
      'Email':    $.trim($('#ContactEmail').val()),
      'Phone':    $.trim($('#ContactPhone').val()),
      'Company':  $.trim($('#ContactCompany').val()),
      'Comments': $.trim($('#ContactComments').val())
    }
    
    // Make sure name and either email or phone have been provided
    if(!contact['Name']) {
      $('#ContactName').focus()
      return show_message('Please provide your name.', 'error')
    }
    
    if(!contact['Email'] && !contact['Phone']) {
      if(!contact['Email']) $('#ContactEmail').focus()
      return show_message('Please provide either an email address or a phone number.', 'error')
    }
    
    if(!contact['Comments']) {
      $('#ContactComments').focus()
      return show_message('Your forgot to enter a message.', 'error')
    }
    
    // Send data to server
    $.post("contact.php", contact, function(data) {
        if(data == 'success') {
          
          // Success!
          show_message('Thank you for contacting us.<br />We will get back to you shortly!', 'success')

          $('#ContactForm').addClass('contactJustSent');
          setTimeout(hide, 4000)
          
        } else {
          
          // Uh oh!
          show_message('Uh oh, something went wrong. Please try again later.', 'error')
        }
    })
    
  }  
  

  return {
    toggle: toggle,
    submit: submit
  }

}()


var AssessmentForm = function() {
  
  var _captcha = {};
  
  $(window).load(function() {
    if($('#AssessmentForm').size() == 0) return
    _captcha = new InvisibleCaptcha('#AssessmentForm')
  })
  
  
  var show_message = function(message, className) {
    
    if(!message) {
      $('#AssessmentMessage').hide()
    }
    else {
      $('#AssessmentMessage').removeClass()
      if(className) $('#AssessmentMessage').addClass(className)
      $('#AssessmentMessage').html(message)
      $('#AssessmentMessage').show()
    }
  }
  

  /***************
  PUBLIC FUNCTIONS
  ***************/
  var submit = function() {
    show_message(false)
    
    if(!_captcha.verify()) {
      return show_message('Please fill in the form before submitting.', 'error')
    }
    
    var contact = {
      'Name':     $.trim($('#AssessmentName').val()),
      'Email':    $.trim($('#AssessmentEmail').val()),
      'Phone':    $.trim($('#AssessmentPhone').val()),
      'Company':  $.trim($('#AssessmentCompany').val()),
      'Comments': $.trim($('#AssessmentComments').val())
    }
    
    // Make sure name and either email or phone have been provided
    if(!contact['Name']) {
      return show_message('Please provide your name.', 'error')
    }
    
    if(!contact['Email'] && !contact['Phone']) {
      return show_message('Please provide either an email address or a phone number.', 'error')
    }
    
    // Send data to server
    $.post("assessment.php", contact, function(data) {
        if(data == 'success') {
          
          // Empty fields
          $('#AssessmentName').val('')
          $('#AssessmentEmail').val('')
          $('#AssessmentPhone').val('')
          $('#AssessmentCompany').val('')
          $('#AssessmentComments').val('')

          // Success!
          show_message('Thank you for contacting us. We will get back to you shortly!', 'success')
          
        } else {
          
          // Uh oh!
          show_message('Uh oh, something went wrong. Please try again later.', 'error')
        }
    })
    
  }

  return {
    submit: submit
  }

}()



jQuery.fx.step['backgroundPosition'] = function(fx) {
	if (!fx.bgPosReady) {
		var start = fx.elem.style.backgroundPosition
		if(!start) start = [0, 0]
		start = start.split(' ')
		fx.start = [parseInt(start[0]), parseInt(start[1])]
		
		var end = fx.options.curAnim.backgroundPosition.replace('(', '').split(' ')
		fx.end = [parseInt(end[0]), parseInt(end[1])]
		
		fx.bgPosReady = true
	}

  var new_pos = [ ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0],
                  ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] ]
  
  if(jQuery.browser.safari || jQuery.browser.msie)
    fx.elem.style.backgroundPosition = Math.floor(new_pos[0])+'px '+Math.floor(new_pos[1])+'px'
  else
    fx.elem.style.backgroundPosition = new_pos[0]+'px '+new_pos[1]+'px'
}