;(function($) {
  $.fn.equalHeights = function() {
    var h = 0;

    this.delay(5000).each(function(i) {
      h = Math.max(h, $(this).outerHeight(true));
    }).height(h);    
  }

  $.fn.popup = function(options) {
    return this.each( function() {
      $(this).click(function(e) {
        e.preventDefault();
        window.open(this.href, options.name, 'width='+ options.width +', height='+ options.height +', directories=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no').focus();
      });
    });    
  }

  $.fn.target_blank = function() {
    return this.each( function() {
      $(this).click(function(e) {
        e.preventDefault();
        window.open(this.href, '_blank').focus();
      });
    });    
  }

  $.fn.current_navigation = function() {
    return this.each( function() {
      if (location.pathname.match('^' + $(this).attr('href') + '$')) {
        $(this).addClass('current');
      }
    });    
  }

  $.fn.fancybox_form = function(options) {
    var defaults = {
      autoDimensions : false,
      width          : 480,
      padding        : 0,
      titleShow      : false,
      overlayOpacity : 0.8,
      scrolling      : 'no',
      overlayColor   : '#000'
    }
    
    options = $.extend({}, defaults, options);
    
    // Force the ajax view
    var href = $(this).attr('href') + "?is_ajax=1";
    $(this).attr('href', href);

    return $(this).fancybox(options);
  }


  // Site Specific Scripts
  site = {
    child_selectors: function() {
      $('#navigation li:first-child').css('padding', 0);
      $('.home #blog .post:last-child').css('border-right', 0);
    },

    launch_audioplayer: function() {
      $('#launch-audioplayer').popup({name:'audioplayer', width:280, height:120}).click(function() {
        $('#header').append($('#audioplayer').remove().clone());
      });
      
      $("a[href*='.mp3']").each(function() {
        file = $(this).attr('href').split(document.domain)[1];
        $(this).attr('href', '/audioplayer/?file=' + file + '&title=' + $(this).html());
        $(this).popup({name:'audioplayer', width:280, height:120}).click(function() {
          $('#header').append($('#audioplayer').remove().clone());
        });        
      });    
    },

    countdown: function() {
      var launch = new Date(2010,6,23);
      
      $('#masthead-ticker').hide().countdown({
        until:   launch,
        layout: '{d<}{dn} Days | {d>}{hn} Hours | {mn} Mins | {sn} Secs'
      }).delay(2000).fadeIn();
    },

    style_images: function() {
      // Wrap a container around uploaded images
      $('#content .post img').each(function() {
        $(this).wrap('<div class="image-container" />');
      });

      // Put the homepage images in a background to v-align them
      $('.home .entry-image').each(function() {
        var img = $(this).find('img').remove();

        $(this).css({
          'background' : "#E4EBE9 url('"+img.attr('src')+"') no-repeat 0 50%"
        });
      });
    },

    external_links: function() {
      $("a[href^='http://']").each( function() {
        if (!$(this).attr('href').match(document.domain)) {
          $(this).target_blank();
        };
      });
    },
    
    subscribe: function() {
      var valid_email = /^((([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;


      // Observe the form is accessed directly
      if ($('.subscribe-form').size()) {
        observe_form();
      };

      // Handle clicking on the fancybox link
      $('a[href*=/subscribe/]').fancybox_form({onComplete : function() {
        $.fancybox.resize();        
        observe_form();
      }});


      function observe_form() {
        $(".subscribe-form").each( function() {
          var email   = $(this).find('input[name=YMP0]');           
          var country = $(this).find('select[name=YMP1]');
          var state   = $(this).find('select[name=YMP5]');
          var submit  = $(this).find('input[type=submit]');

          country.change(function() {
            if ($(this).val() == 'Australia') {
              state.parent().show();
            } else {
              state.parent().hide();
              state.find('option').removeAttr('selected').first().attr('selected', 'selected');
            }
            $.fancybox.resize();
          });

          $(this).submit( function() {
            submit.attr('disabled', 'disabled');

            // validate the email
            if (!valid_email.test(email.val())) {
              var error = $('<div>').addClass('email-error error').html('Please enter a valid email address.');
              
              if ($('.email-error').size()) {
                $('.email-error').replaceWith(error);
              } else {
                error.insertAfter(email);
              }

              submit.removeAttr('disabled');
              $.fancybox.resize();
              return false;
            }
          });
        });
      }
    },

    contact: function() {
      $('#contact').fancybox_form({onComplete : observe_form});
      
      function observe_form() {
        $.fancybox.resize();

        $("#fancybox-inner form").submit( function() {
          $(this).find('input[type=submit]').attr('disabled', 'disabled');
          $.fancybox.showActivity();
          $.post($(this).attr('action'), $(this).serialize(), function(data) {
            $("#fancybox-inner #container").replaceWith(data);
            $.fancybox.hideActivity();
            observe_form();
          });

          return false;
        });
      }      
    },

    buy_now: function() {
      $("a:contains('Buy Now')").addClass('button');
    }
  }
})(jQuery);


jQuery(function($) {
  // Tout slideshow
  $('#touts').cycle({timeout: 5000});
  
  // Make the homepage blog equal heights
  $('#blog .post').equalHeights();
  
  // Set the current navigation item
  $('#navigation a').current_navigation();
    
  // Audioplayer popup
  site.launch_audioplayer();
  
  // Enforce :first-shild :last-child css rules
  site.child_selectors();
  
  // Make the images look good
  site.style_images();
  
  // Make links to differnt domain open in a new window
  site.external_links();
  
  // Subscribe popup
  site.subscribe();
  
  // Contact popup
  site.contact();
  
  // Add style to Buy Now links
  site.buy_now();
});
