$(document).ready(function() {

  var $html = $('html');
  var $body = $('body');
  var body_id = $body.attr('id');
  
  if (!Modernizr.fontface) $body.prepend('<div id="fontface"><p>Warning! Your browser does <strong>not</strong> support web fonts. Your experience with the Merry Newsinator will be severely crippled. Please upgrade to a <a href="https://typekit.assistly.com/customer/portal/articles/6786#kb_article_body">recommended browser</a> for the best possible experience.</p></div>');

  // --------------------------------------------------------------------------
  // The Landing Page

  if (body_id === 'p_intro')
  {
    $('ol li').each(function(i) {
      var num = parseInt(i, 10) + 1;
    
      $(this).prepend('<i>'+ num +'</i>');
    });
  }

  // --------------------------------------------------------------------------
  // The Questionnaire

  if (body_id === 'p_quest')
  {
    // Gears!
    $body.append('<div id="gears"><i id="gear1"></i><i id="gear2"></i><i id="gear3"></i></div>');
    
    // Superfluous classes
    $('fieldset:first').addClass('first');
    $('fieldset').each(function() { $(this).find('p:first').addClass('first'); });
    
    // Replace all select elements for styling
    var $selects = $('select');
    
    if (!$html.hasClass('ie7') && !$html.hasClass('ie6')) {
      $selects.sSelect();
      $selects.each(function() {
        var $select = $(this);
        var $links = $select.next().find('li a');
      
        // Hide the repeated (but necessary) element
        // Call the next one the first one
        $links.eq(0).hide();
        $links.eq(1).addClass('first');
      });
    }
    else {
      $selects.parent().addClass('clearfix');
    }
    
    // Either Or
    $('#either_or a').click(function(e) {
      e.preventDefault();
    
      var $this = $(this);
      var $parent = $this.parent();
    
      // Remove sibling's selected class
      $parent.find('.selected').removeClass('selected');
    
      // Add selected class to clicked
      $this.addClass('selected');
    
      // Set hidden input's value
      $('p.hidden input[name="'+ $parent.attr('id') +'"]').val($this.text());
    });
    
    // Show selections when editing
    if ($('#either_or_selections input:first').val() !== '') {
      $('#either_or_selections input').each(function() {
        var $this = $(this);
        var selection = $this.val();
        
        $('#'+$this.attr('name')+' a').each(function() {
          var $link = $(this)
          var text = $link.text();
          
          if (text === selection) $link.addClass('selected');
        });
      });
    }
  
    // Write your own
    $('#closing').change(function() {
      var $this = $(this);
      var $closing = $('#closing');
    
      if ($this.val() === 'Write your own...') {
        // enable/disable the input
        $('#custom_closing').focus();
      }
    });
    
    function toggleGearAnimation() {
      if (Modernizr.cssanimations) {
        $('#gear1, #gear2, #gear3').toggleClass('animated');
      }
    }
    
    // Hide the alert message
    $('#alert a').click(function(e) {
      e.preventDefault();
      $('#tranny').fadeOut();
      toggleGearAnimation();
    });
    
    // Check the form for completeness
    $('form').submit(function() {
      toggleGearAnimation();
      
      var $tranny = $('#tranny');
      var $inputs = $('input:text');
      var has_errors = false;
      
      $inputs.each(function() {
        var $this = $(this);

        if ($this.attr('id') === 'custom_closing') {
          var $closing = $('#closing');
          var $options = $closing.find('option');
          
          if ($options.eq($closing.val()).text() === '' && $this.val() === '') {
            $this.addClass('error');
            has_errors = true;
          }
        }
        else {
          var is_not_filled_out = ($this.val() === '');
          
          if (is_not_filled_out) {
            $this.addClass('error');
            has_errors = true;
            
            $this.bind('focus blur', function() {
              var is_not_filled_out = ($this.val() === '');
              if (!is_not_filled_out) $this.removeClass('error');
            });
          }
        }
      });
      
      if (has_errors) {
        if ($html.hasClass('ie6')) {
          var $window = $(window);
          
          $tranny.css({
            height: $window.height()+'px',
            width: $window.width()+'px'
          });
        }
        
        $tranny.fadeIn();
        return false;
      }
      else {
        return true;
      }
    });
  }

  // --------------------------------------------------------------------------
  // The Preview Page

  if (body_id === 'p_preview')
  {
    var $tranny = $('#tranny');
    var $cancel = $('#cancel a');
    
    function finalize() {
      newsinator.save();
      
      $tranny.fadeIn();
    }
    
    function shareLinkViaService(link, service) {
      var message;
      
      switch(service) {
        case 'email':
          message = 'I just made the best holiday newsletter ever with the Merry Newsinator from Plaid! You can too. Share with friends and lift spirits like a helium filled menorah';
          
          window.location = 'mailto:?subject=The Merry Newsinator&body='+encodeURI(message+'\n\n'+link+'\n\n');
          break;
        
        case 'twitter':
          message = 'I just made the best holiday newsletter ever with the Merry Newsinator from @Plaidinc! You can too. #merrynews';
          
          window.open('http://twitter.com/share?text='+encodeURI(message)+"&url="+encodeURI(link),'sharer','toolbar=0,status=0,resizable=0,width=626,height=436');
          break;
        
        case 'facebook':
          message = 'I just made the best holiday newsletter ever with the Merry Newsinator from Plaid! You can too.';
          Facebook.share(link,message);
          break;
      }
    }
    
    function printNewsinator() {
      var $browser = $.browser;
      var is_chrome = (navigator.appVersion.indexOf('Chrome') != -1);
      var p = false;
      
      if ($browser.mozilla || is_chrome) {
        if (confirm("Unfortunately, your browser does not support the printing of background colors and images. So, your lovingly Newsinated newsletter will lack the pizzazz you see on your screen. We recommend using a different browser (Safari or Opera will do nicely).\n\nPress 'OK' to print anyways, or 'Cancel' and use a different browser.")) p = true;
      }
      else {
        if ($browser.safari) {
          if (confirm("For optimal Newsination, please ensure Safari’s 'Print Backgrounds' setting is enabled when printing. If you need help, please select 'Cancel' and visit:\nhttp://support.apple.com/kb/TS2166\n\nPress 'OK' to continue printing…"))
            p = true;
        }
        else if ($browser.msie) {
          var v = $browser.version.charAt(0);
          var step_2;
          
          if (v === '9' || v === '8')
            step_2 = "http://support.microsoft.com/kb/975455";
          else
            step_2 = "http://support.microsoft.com/kb/296326";
          
          if (confirm("For optimal Newsination, please ensure Internet Explorer’s 'Print Background Colors and Images' feature is enabled before printing. If you need help, please select 'Cancel' and visit:\n"+ step_2 +"\n\nPress 'OK' to continue printing…"))
            p = true;
        }
        else {
          p = true;
        }
      }
      
      if (p) print();
    }
    
    $('#actions a, #share li a').click(function(e) {
      e.preventDefault();
      var href = $(this).attr('href');
      var action = href.substring(1, href.length);
      
      var hash = window.location.hash;
      var link = 'http://merrynewsinator.com/'+ hash.substring(2, hash.length);
      
      switch(action) {
        case 'refresh': break; // in newsinator.js
        case 'edit': $('#edit').submit(); break;
        case 'finalize': finalize(); break;
        
        case 'email': shareLinkViaService(link, 'email'); break;
        case 'print': printNewsinator(); break;
        case 'twitter': shareLinkViaService(link, 'twitter'); break;
        case 'facebook': shareLinkViaService(link, 'facebook'); break;
      }
    });
  
    $cancel.text('x');
    $cancel.click(function(e) {
      e.preventDefault();
      $tranny.fadeOut();
    });
  }

  // --------------------------------------------------------------------------
  // IE

  if ($html.hasClass('ie7') || $html.hasClass('ie8') || $html.hasClass('ie6'))
  {
    if ($html.hasClass('ie6')) alert('Thanks for taking a look at the Merry Newsinator. Unfortunately, we do not support your browser. Please upgrade your browser and return. Thanks!\n\nWe recommend the browsers you\'ll find at http://upgradeyourbrowser.net.');
    
    if (body_id === 'p_intro')
    {
      $('ol li').each(function(i) {
        var count = parseInt(i, 10) + 1;
        $(this).addClass('child_'+ count);
      });
    }
  
    if (body_id === 'p_quest')
    {
      var $text_inputs = $('input:text');
      $text_inputs.addClass('text');
      $text_inputs.bind('focus blur', function(e) {
        var $this = $(this);
        
        if (e.type === 'focus') $this.addClass('focus');
        else $this.removeClass('focus');
      });
      
      $('input:submit').addClass('submit');
      $('.inline').each(function() { $(this).find('label:first').addClass('first'); });
    }
  }

});

/* array randomize, based on Fisher-Yates shuffle algorithm */
Array.prototype.randomize=function(){var i=this.length;if(i==0)return false;while(--i){var j=Math.floor(Math.random()*(i+1));var tempi=this[i];var tempj=this[j];this[i]=tempj;this[j]=tempi}};
