var prev_page_id = 'home';
var prev_method_section = 'overview';
var default_page = prev_page_id;
jQuery.easing.def = "easeOutQuad";

var sections = ['home','portfolio','method','contact','privacy'];
var clients = ['aol / time warner','dean &amp; deluca','dj mark farina','ibm','j.h. whitney &amp; co.','johnson &amp; johnson','liberty financial','mad magazine','nullsoft','palio communications','philips','ralph lauren','red bull uk','sony/bmg','the recording academy','universal studios','warner bros'];

// fancybox vars
var fb_hide_click_off = { hideOnContentClick: false };

function getAppStoreUrl(app_name) {
  if(app_name.indexOf("Count Sheep") != -1)
    return '<a href="itms://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=317530000" target="itunes_target"><img src="/images/folio/appstore.png" align="absmiddle" /></a>';
  else
    return '<a href="itms://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=322878151" target="itunes_target"><img src="/images/folio/appstore.png" align="absmiddle" /></a>';
}

function showExclam($for_obj) {
  var isIE = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 8);
  
  var start_x = ($for_obj.attr('name') == 'bos7kz') ? '352px' : '210px';
  var offset_x_ie = 0;
  if(isIE && $for_obj.attr('name') != 'lpqoo4')
    offset_x_ie = 0;
  var end_x = ($for_obj.attr('name') == 'bos7kz') ? (372 + offset_x_ie) + 'px' : (230 + offset_x_ie) + 'px';
  
  var $exclam = $for_obj.parent().find('div.exclam:first');
  if($exclam.css('display') != 'none') return false;
  $exclam.css({ left: start_x, opacity: 0, display: 'block' });
  $exclam.animate({ left: end_x, opacity: 0.99 }, 600, 'easeOutElastic');
  
  $for_obj.css({ border: '1px solid #bebebe' });
}

function hideExclam($for_obj) {
  var $exclam = $for_obj.parent().find('.exclam:first');
  if($exclam.css('display') != 'none') {
    $exclam.fadeOut(200);
    $for_obj.css({ border: '1px solid #696969' });
  }
}

function validEaddr(email) {
  return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
}

$(window).load(function() {
  // preload those images!
  if(default_page != 'portfolio') {
    var portfolio_thumbs_img = new Image();
    portfolio_thumbs_img.src = "/images/folio/thumbs.jpg";
  }
  if(default_page != 'method') {
    var method_buttons_img = new Image();
    method_buttons_img.src = "/images/method-buttons.jpg";
  }
  if(default_page != 'home') {
    var home_img = new Image();
    home_img.src = "/images/pic-home.jpg";
  }
  
  
  //
  // logo click handler
  //
  $('#tb_logo').click(function(e) {
    document.location = 'http://www.taberbuhl.com';
  });
  
  
  //
  // navigation handlers
  //
  $('#nav ul li').hover(function(e) {
    var $this = $(this);
    if($this.children().eq(0).hasClass('active')) return;

    $this.css({ background: '#333333' }); // safari fix, wee!
    $this.animate({ backgroundColor: '#53534d' }, 250);
  },
  function(e) {
    var $this = $(this);
    if($this.children().eq(0).hasClass('active')) return;
    
    $this.stop();
    $this.css({ backgroundColor: 'transparent' });
  });
  $("#nav ul li div").click(function(e){
    var $this = $(this);
    
    e.preventDefault();
    e.stopPropagation();

    //var $this = $(e.target).parent().parent();
    //alert(e.target.innerHTML);
        
    $this.parent().parent().children().each(function(i) {
      $(this).stop().css({ backgroundColor: 'transparent' });
    });
    
    if($this.hasClass('active')) return;

    onClickNav($this.attr('id'), true);
  });


  //
  // override the browser's history method
  //
  $(window).history(function(e, hash) {
    if(jQuery.inArray(hash, sections))
      onClickNav('nav_' + hash, true);
    else
      onClickNav('nav_home', true);
  });
  
  // init section if user visits a #section "organically" as the kids say
  var cur_history = $.history.getCurrent();

  if(cur_history.length > 1 && jQuery.inArray(cur_history, sections)) {
    onClickNav('nav_' + cur_history, false);
    default_page = cur_history;
  }
  
  
  //
  // contact form handlers
  //
  var $contact_inputs = $('#contact dl dd :input');
  $contact_inputs.focus(function(e) {
    $(this).addClass('focused');
  })
  .blur(function(e){
    $(this).removeClass('focused');
  });
  
  var $contact_form = $('#contact_form');
  var $contact_form_discuss = $('#lpqoo4');
  var $req_inputs = $('#contact_form :input.req');
  
  $contact_form_discuss.change(function(e) {
    var $this = $(e.target);
    if($this[0].selectedIndex < 1)
      showExclam($this);
    else
      hideExclam($this);
  });
  
  $req_inputs.keyup(function(e) {
    if(!form_submitted) return false;
    
    $this = $(e.target);
    if(($this[0].tagName.toLowerCase() == 'select' && $this[0].selectedIndex < 1) || ($this[0].tagName.toLowerCase() != 'select' && $this.val().length < 2)) {
      showExclam($this);
      return false;
    }
    if($this.attr('id') == 'meoalo' && !validEaddr($this.val())) {
      showExclam($this);
      return false;
    }
    
    hideExclam($this);    
  });
    
  
  //
  // portfolio handlers
  //
  var $folio_thumbs = $('#portfolio dl dd ul li img.thumb');
  $folio_thumbs.each(function(){ $(this).css({ cursor: 'pointer' }); });
  $folio_thumbs.mouseover(function(e){
    var $thumb = $(this);
    if(!$thumb.hasClass('logo'))
      $thumb.addClass('active');
    $thumb.parent().parent().animate({ opacity: 0.99 }, 666);
  }).mouseout(function(e){
    var $thumb = $(this);
    if(!$thumb.hasClass('logo'))
      $thumb.removeClass('active');
    $thumb.parent().parent().stop();
    $thumb.parent().parent().css({ opacity: 0.6 });
  });
  
  var items = {};
    
  items = { itemArray: [
    { href: '/images/folio/greenhouse_1.jpg', title: 'Greenhouse Reps 1/3 ::1::0::1::' },
    { href: '/images/folio/greenhouse_2.jpg', title: 'Greenhouse Reps 2/3 ::1::0::1::' },
    { href: '/images/folio/greenhouse_3.jpg', title: 'Greenhouse Reps 3/3 ::1::0::1::' }
  ] };
  $('#greenhouse a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/mccaul_1.jpg', title: 'Andrew McCaul Photography 1/2 ::1::0::0::' },
    { href: '/images/folio/mccaul_2.jpg', title: 'Andrew McCaul Photography 2/2 ::1::0::0::' }
  ] };
  $('#amccaul a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/presstube_1.jpg', title: 'Presstube 1/2 ::1::1::1::' },
    { href: '/images/folio/presstube_2.jpg', title: 'Presstube 2/2 ::1::1::1::' }
  ] };
  $('#presstube a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/winamp_1.jpg', title: 'Winamp 1/4 ::1::1::1::' },
    { href: '/images/folio/winamp_2.jpg', title: 'Winamp 2/4 ::1::1::1::' },
    { href: '/images/folio/winamp_3.jpg', title: 'Winamp 3/4 ::1::1::1::' },
    { href: '/images/folio/winamp_4.jpg', title: 'Winamp 4/4 ::1::1::1::' }
  ] };
  $('#winamp a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/palio_1.jpg', title: 'Palio Communications 1/2 &nbsp;&nbsp;&nbsp; Award: <a href="http://www.canneslions.com/" target="_blank"><img src="/images/award-cannes.gif" align="absmiddle" /></a> ::1::1::1::' },
    { href: '/images/folio/palio_2.jpg', title: 'Palio Communications 2/2 &nbsp;&nbsp;&nbsp; Award: <a href="http://www.canneslions.com/" target="_blank"><img src="/images/award-cannes.gif" align="absmiddle" /></a> ::1::1::1::' }
  ] };
  $('#palio a').fancybox($.extend(items, fb_hide_click_off));
  
  $('#thumbs_logos li a').fancybox();
  
  items = { itemArray: [
    { href: '/images/folio/grammys_1.jpg', title: 'Grammy Magazine 1/2' },
    { href: '/images/folio/grammys_2.jpg', title: 'Grammy Magazine 2/2' }
  ] };
  $('#grammys a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/health_1.jpg', title: 'Johnson &amp; Johnson Health Illustration 1/1' }
  ] };
  $('#health a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/airtroductions_1.jpg', title: 'Airtroductions Illustration 1/2' },
    { href: '/images/folio/airtroductions_2.jpg', title: 'Airtroductions Illustration 2/2' }
  ] };
  $('#airtroductions a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/red-bull-x-fighters_1.jpg', title: 'Red Bull X-Fighters Safety Card 1/2' },
    { href: '/images/folio/red-bull-x-fighters_2.jpg', title: 'Red Bull X-Fighters Safety Card 2/2' }
  ] };
  $('#xfighters a').fancybox(items);
  
  $('#foofighters a').fancybox();
  
  items = { itemArray: [
    { href: '/images/folio/skins_classic_1.jpg', title: 'Classic Winamp Skins 1/5' },
    { href: '/images/folio/skins_classic_2.jpg', title: 'Classic Winamp Skins 2/5' },
    { href: '/images/folio/skins_classic_3.jpg', title: 'Classic Winamp Skins 3/5' },
    { href: '/images/folio/skins_classic_4.jpg', title: 'Classic Winamp Skins 4/5' },
    { href: '/images/folio/skins_classic_5.jpg', title: 'Classic Winamp Skins 5/5' },
    { href: '/images/folio/skins_classic_6.jpg', title: 'Classic Winamp Skins 6/5' }
  ] };
  $('#skins_classic a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/skins_modern_1.jpg', title: 'Modern Winamp Skins 1/8 (Bento)' },
    { href: '/images/folio/skins_modern_2.jpg', title: 'Modern Winamp Skins 2/8 (Motorola C330)' },
    { href: '/images/folio/skins_modern_3.jpg', title: 'Modern Winamp Skins 3/8 (Nokia 3250)' },
    { href: '/images/folio/skins_modern_4.jpg', title: 'Modern Winamp Skins 4/8 (Playboy)' },
    { href: '/images/folio/skins_modern_5.jpg', title: 'Modern Winamp Skins 5/8 (Bacardi)' },
    { href: '/images/folio/skins_modern_6.jpg', title: 'Modern Winamp Skins 6/8 (Lord of The Rings)' },
    { href: '/images/folio/skins_modern_7.jpg', title: 'Modern Winamp Skins 7/8 (MAD Magazine)' },
    { href: '/images/folio/skins_modern_8.jpg', title: 'Modern Winamp Skins 8/8 (Coldplay)' }
  ] };
  $('#skins_modern a').fancybox(items);
  
  items = { itemArray: [
    { href: '/images/folio/iphone_cs_1.jpg', title: 'Count Sheep 1/4' },
    { href: '/images/folio/iphone_cs_2.jpg', title: 'Count Sheep 2/4' },
    { href: '/images/folio/iphone_cs_3.jpg', title: 'Count Sheep 3/4' },
    { href: '/images/folio/iphone_cs_4.jpg', title: 'Count Sheep 4/4' }
  ] };
  $('#countsheep a').fancybox($.extend(items, fb_hide_click_off));
  
  items = { itemArray: [
    { href: '/images/folio/iphone_po_1.jpg', title: 'Plus One 1/2' },
    { href: '/images/folio/iphone_po_2.jpg', title: 'Plus One 2/2' }
  ] };
  $('#plusone a').fancybox($.extend(items, fb_hide_click_off));
  
  
  //
  // method button handlers
  //
  var $method_buttons_parent = $('#method_buttons');
  var prev_method_button = '';
  $method_buttons_parent.live('mouseover', function(e) {
    if(e.target.tagName.toLowerCase() != 'img') return;
    
    e.preventDefault();
    
    var $this = $(e.target).parent().parent();

    if(!$this.hasClass('active'))
      $this.addClass('over');
  }).live('mouseout', function(e) {
    if(e.target.tagName.toLowerCase() != 'img') return;
    
    e.preventDefault();
    
    var $this = $(e.target).parent().parent();    
    $this.removeClass('over');
  });
  $method_buttons_parent.live('click', function(e){
    if(e.target.tagName.toLowerCase() != 'img') return;
    
    e.preventDefault();
    
    var $this = $(e.target).parent().parent();
    
    var method_section = $this.attr('id');
    method_section = method_section.replace(/method_button_/, '');
    if(prev_method_section == method_section)
      return;
    
    // remove active image state from previous method button
    var $prev_method_button = $('#method_button_' + prev_method_section);
    $prev_method_button.removeClass('active');
    
    // set the active state for the button that was clicked
    $this.removeClass('over').addClass('active');
    
    // fade out previous method content
    $('#method_' + prev_method_section).fadeOut();
    
    // fade in current method content
    var $method_section = $('#method_' + method_section);
    $method_section.css({ left: '505px', opacity: 0, display: 'block' });
    $method_section.animate({ left: '0px', opacity: 1 }, 300);
    
    prev_method_section = method_section;
  });
    
});

var contact_form_item_focused = false;
var form_submitted = false;
function onSubmitContact(form_id) {
  contact_form_item_focused = false;
  form_submitted = true;
  
  // check for blank required fields
  $('#contact_form :input.req').each(function() {
    $this = $(this);
    if(($this.attr('id') == 'meoalo' && !validEaddr($this.val())) || ($this[0].tagName.toLowerCase() == 'select' && $this[0].selectedIndex < 1) || ($this[0].tagName.toLowerCase() != 'select' && $this.val().length < 2)) {
      showExclam($this);
      if(!contact_form_item_focused){
        $this.focus();
        contact_form_item_focused = true;
      }
    }
  });
  
  if($(form_id).find('div.exclam:visible').size() > 0)
    return false;
}

function getContactLink() {
  var ml = 't fl/b.iu=oha?@rmncj\"<>sCe:';
  var mi = 'E<1;?I29D@<730:J0<5I?>0<5I?58;36B:@=G85CIB09H:A0<B0DF0<5I?>0<5I?58;36B:@E4<F';
  var ot = '';
  for(j = 0; j < mi.length; j++) {
    ot += ml.charAt(mi.charCodeAt(j) - 48);
  }
  return ot;
}

function onClickNav(id, add_to_history) {

  if($(id).hasClass('active'))
    return false;
  
  var new_page_id = id.replace('nav_', '');
      
  if(new_page_id == prev_page_id)
    return false;

  var $prev_id = $('#'+prev_page_id);
  var $new_id = $('#'+new_page_id);
  
  var $prev_nav_id = $('#nav_'+prev_page_id);
  var $new_nav_id = $('#nav_'+new_page_id);
  
  var $prev_section_id = $('#section_'+prev_page_id);
  var $new_section_id = $('#section_'+new_page_id)
  
  // update history and hide footer benchmark on subsequent page loads only
  if(add_to_history) {
    if($('#benchmark').is(':visible'))
      $('#benchmark').fadeOut();
    $.history.add(new_page_id);
  }
  
  // update body
  $prev_id.removeClass('active');
  $prev_id.hide();
  $new_id.fadeIn();

  // update nav
  $prev_nav_id.removeClass('active');
  $new_nav_id.addClass('active');

  // update section image
  $prev_section_id.hide();
  $new_section_id.show();

  // update other page elements
  var $right = $('#right');
  if(new_page_id == 'home') {
    $right[0].innerHTML = '<img class="pic_home" src="/images/pic-home.jpg" alt="Fig. 1a - Taber Buhl" />';
  }else if(new_page_id == 'portfolio') {
    var clients_html = '<ul class="clients"><li class="first">Clients:</li>';
    for(var i = 0; i < clients.length; i++) {
      clients_html = clients_html + '<li>' + clients[i] + '</li>';
    }
    $right.html(clients_html);
  }else if(new_page_id == 'method') {
    // hide any previously loaded method sections
    $('#method dl.method').hide();
    $('#method_overview').show();
    prev_method_section = 'overview';
    
    var method_html = '<ul id="method_buttons" class="method_buttons">';
    method_html += '<li id="method_button_inception"><a href="/method/" onfocus="this.blur()"><img src="/images/shim.gif" /></a></li>';
    method_html += '<li id="method_button_mockuprocket"><a href="/method/" onfocus="this.blur()"><img src="/images/shim.gif" /></a></li>';
    method_html += '<li id="method_button_hammertime"><a href="/method/" onfocus="this.blur()"><img src="/images/shim.gif" /></a></li>';
    method_html += '<li id="method_button_delivery"><a href="/method/" onfocus="this.blur()"><img src="/images/shim.gif" /></a></li>';
    method_html += '</ul>';
    $right.html(method_html);  
  }else if(new_page_id == 'contact') {
    var contact_html = '<ul class="contact_info">';
    
    var ot = getContactLink();
    if(ot)
      contact_html += '<li id="email">' + ot + '</li>';
    contact_html += '<li id="phone" class="first">+1 (315) Y&Oslash; TABER</li>';
    contact_html += '<li id="fax">+1 (502) 371-7351</li>';
    contact_html += '</ul>';
    $right.html(contact_html);
  }

  prev_page_id = new_page_id;

  return false;
}
