function decodeURIFully(uri) {
  return decodeURIComponent(uri.replace(/\+/, ' '));
}

// Super duper simple form validation
function simpleValidation(form) {
  var errors = 0,
      form = $(form);
  form.find('.required input').each(function() {
    if (($(this).attr("type") == "text" && $(this).attr('value') == '') || ($(this).attr("type") == "checkbox" && !$(this).attr('checked'))) {
      errors += 1;
      $(this).closest('li').addClass('error');
    } else {
      $(this).closest('li').removeClass('error');
    }
  });
  if (errors > 0) {
    alert('Please fix the highlighted form fields and submit the form again. Thanks!');
    return false;
  } else {
    return true;
  }
}


$(document).ready(function() {
  // Push Page Phone Switcher
  $('#push-handsets li').click(function(event) {
    var parent   = $(this).closest('div');
    var siblings = $(this).siblings();
    var index    = $(this).index();
    var position = -200 * index;
    event.preventDefault();
    if (!$(this).hasClass('current')) {
      $(this).addClass('current');
      siblings.removeClass('current');
      parent.animate({'backgroundPosition': position + "px 0"}, 200);
    }
  });
  $('#push-handsets li:first-child').addClass('current');
  
  // Customers Navigation for the script enabled
  if (typeof(customers) != undefined && $('body').hasClass('customers')) {
    if (window.innerWidth > 480) {
      // Remove styling for folks that have JS enabled
      $('#left-navigation li:first-child').addClass('current-menu-item');
      $('#left-navigation ul').removeClass('static'); 
      // Add JS switchy goodness
      $('#left-navigation a').click(function(event) {
        var nav_item   = $(this).closest('li'),
            item_index = nav_item.index();
        event.preventDefault();
        nav_item.addClass('current-menu-item').siblings().removeClass('current-menu-item');
        $('#guts').html(customers[item_index]);
      });
    } else {
      
      var buttons = (buttons == null) ? false : true;
      var container = $('#case-studies');
      var containerWidth = container.width();
      var slideContainer = $('<ul/>');
      var slideNav = $('<ul class="slide-nav"></ul>').insertBefore('#case-studies > h2');
      var slideArrows = $('<li class="flippers"><a href="#" class="previous">Previous</a> <a href="#" class="next">Next</a></li>').appendTo(slideNav);
      var slideMoved = 0;
      var slideLength = customers.length - 1;
      for (var i = 0, n = slideLength; i < n; i++) {
        $('<li>').css({"width": container.width() + "px", "float": "left"}).html($(customers[i]).find('div:first-child')).prepend($('<h2>' + $('#left-navigation ul li a').eq(i).text() + '</h2>')).appendTo(slideContainer);
      }
      slideContainer.width(100 * slideLength + "%").attr('id', 'case-study-slider').appendTo('#case-studies');
      slideArrows.find('.previous').addClass('disabled').click(function(event) {
        event.preventDefault();
        if (!(slideContainer.is(':animated') || $(this).hasClass('disabled'))) {
          slideMoved--;

          if (slideMoved < slideLength) {
            slideContainer.animate({marginLeft: -100 * slideMoved + '%'});
          }
          if (slideMoved == 0) {
           $(this).addClass('disabled'); 
          }
          if (slideMoved > 0) {
            slideArrows.find('.next').removeClass('disabled');
          }
          if (buttons) {
            var targetButton = $(slideButtons.get(Math.abs(newValue/containerWidth)));
            slideButtons.removeClass('current');
            targetButton.addClass('current');
          }
        }
      });
      slideArrows.find('.next').click(function(event) {
        event.preventDefault();
        if (!(slideContainer.is(':animated') || $(this).hasClass('disabled'))) {
          slideMoved++;

          if (slideMoved < slideLength) {
            slideContainer.animate({marginLeft: -100 * slideMoved + '%'});
          }
          if (slideMoved + 1 == slideLength) {
           $(this).addClass('disabled'); 
          }
          if (slideMoved > 0) {
            slideArrows.find('.previous').removeClass('disabled');
          }
          if (buttons) {
            var targetButton = $(slideButtons.get(Math.abs(newValue/containerWidth)));
            slideButtons.removeClass('current');
            targetButton.addClass('current');
          }
        }
      });
      
      $(window).resize(function(){
        slideContainer.find('li').width(container.width());
      });
    }
  }
  
  // Slides, now set up to be three wide
  function setupSlides(inset, buttons) {
    var buttons = (buttons == null) ? false : true;
    var container = $(inset).find('.slides');
    var containerWidth = container.width();
    var slideContainer = $(inset).find('.slides > ul');
    var slides = $(inset).find('.slides > ul > li');
    var slideNav = $('<ul class="slide-nav"></ul>').insertBefore(container);
    var responsiveLength = (window.innerWidth <= 480) ? slides.length : Math.ceil(slides.length/3);
    // turn on JS styling
    $(inset).addClass('has-js');
    // Set the widths of the elements
    if (window.innerWidth <= 480) {
      slideContainer.css({ width: (100 * slides.length) + "%", left: 0 });
      slides.css({ width: (containerWidth - parseInt(slides.css('paddingRight').replace(/px/, '')) - parseInt(slides.css('paddingLeft').replace(/px/, ''))) });
      $(window).resize(function(){
        slides.width(container.width());
        //containerWidth = container.width();
      });
    } else {
      slideContainer.css({ width: containerWidth * (responsiveLength), left: 0 });
      slides.css({ width: (containerWidth - parseInt(slides.css('paddingRight').replace(/px/, '')) - parseInt(slides.css('paddingLeft').replace(/px/, ''))) / 3 });
    }
    if (buttons) {
      // set up buttons
      slides.each(function() {
        var title = $(this).find('h3').text();
        var newID = title.toLowerCase().replace(/ |\'|\-|\&.+?;/g, '-');
        $('<li><a href="#' + newID + '" id="button_' + newID + '">' + title + '</a></li>').appendTo(slideNav);
      });
    }
    // create arrow buttons and assign behavior
    var slideArrows = $('<li class="flippers"><a href="#" class="previous">Previous</a> <a href="#" class="next">Next</a></li>').appendTo(slideNav);
    slideArrows.find('.previous').click(function(event) {
      event.preventDefault();
      if (!(slideContainer.is(':animated') || $(this).hasClass('disabled'))) {
        var leftValue = parseInt(slideContainer.css('left').replace(/px/, '').replace(/%/, ''));
        var newValue = (window.innerWidth <= 480) ? leftValue + 100 : leftValue + containerWidth;
        var unit = (window.innerWidth <= 480) ? '%' : 'px';
        if (leftValue < 0 ) {
          slideContainer.animate({ left: newValue + unit });
        }
        if (newValue == 0) {
          $(this).addClass('disabled');
        }
        if (leftValue == -(containerWidth * (responsiveLength - 1))) {
          slideArrows.find('.next').removeClass('disabled');
        }
        if (buttons) {
          var targetButton = $(slideButtons.get(Math.abs(newValue/containerWidth)));
          slideButtons.removeClass('current');
          targetButton.addClass('current');
        }
      }
    });
    slideArrows.find('.next').click(function(event) {
      event.preventDefault();
      if (!(slideContainer.is(':animated') || $(this).hasClass('disabled'))) {
        var leftValue = parseInt(slideContainer.css('left').replace(/px/, '').replace(/%/, ''));
        var newValue = (window.innerWidth <= 480) ? leftValue - 100 : leftValue - containerWidth;
        var unit = (window.innerWidth <= 480) ? '%' : 'px';
        if (leftValue > -(containerWidth * (responsiveLength - 1))) {
          slideContainer.animate({ left: newValue + unit });
        }
        if (newValue == ((window.innerWidth <= 480) ? -(slides.length - 1) * 100 : -containerWidth * (responsiveLength - 1))) {
         $(this).addClass('disabled'); 
        }
        if (leftValue == 0) {
          slideArrows.find('.previous').removeClass('disabled');
        }
        if (buttons) {
          var targetButton = $(slideButtons.get(Math.abs(newValue/containerWidth)));
          slideButtons.removeClass('current');
          targetButton.addClass('current');
        }
      }
    });
    if (buttons) {
      // find buttons and assign behavior
      var slideButtons = slideNav.find('li a').not('li.flippers a');
      slideButtons.click(function(event) {
        event.preventDefault();
        var index = slideButtons.index(this);
        var leftValue = parseInt(slideContainer.css('left').replace(/px/, ''));
        var newValue = -containerWidth * index;
        slideContainer.animate({ left: newValue + 'px' });
        slideButtons.removeClass('current');
        $(this).addClass('current');
        if (newValue == 0) slideArrows.find('.previous').addClass('disabled');
        if (newValue < 0) slideArrows.find('.previous').removeClass('disabled');
        if (newValue == -(containerWidth * (slides.length - 1))) slideArrows.find('.next').addClass('disabled');
        if (newValue > -(containerWidth * (slides.length - 1))) slideArrows.find('.next').removeClass('disabled');
      });
      // set up the default states
      slideButtons.filter(':first').addClass('current');
    }
    // set up the default states
    slideArrows.find('.previous').addClass('disabled');
  }
  $('.with-slides').not('.with-buttons').each(function() {
      setupSlides(this, false);
  });
  
  // Left navigation styling updates with the hash. Hashchange only exists as an event in very modern browsers.
  if ($("#left-navigation").length == 1) {
    var links = $("#left-navigation a");
    $(window).bind('hashchange', function() {
      var match = '';
      links.each(function() {
        if ($(this).attr('href') == document.location.hash) {
          match = $(this);
        }
      });
      if (match != '') {
        match.closest('li').addClass('current-menu-item').siblings().removeClass('current-menu-item');
        match.closest('ul').removeClass('static');
      }
    });
  }
  
  // Pardot form error handling: filling in the fields with the submitted values
  if ($("form.validated").length > 0 && document.location.search != '') {
    var query_string = document.location.search.substring(1),
        query_parameters = query_string.split("&"),
        query_length = query_parameters.length,
        query_arguments = {},
        fields = $("form.validated").find('input, select, textarea');
    for (i = 0; i < query_length; i++) {
      var query_parameter = query_parameters[i].split("=");
      query_arguments[query_parameter[0]] = query_parameter[1];
    }
    fields.each(function() {
      if (query_arguments[$(this).attr('name')] != '') {
        if ($(this).is('input')) {
          $(this).attr('value', decodeURIFully(query_arguments[$(this).attr('name')]));
        } else if ($(this).is('select')) {

        } else if ($(this).is('textarea')) {

        }
      }
    });
  }
  // Validation Specifically for the newsletter signup, since we don't want to udpate the styles for that one.
  $("form#newsletter").submit(function(event) {
    var errors = 0;
    $(this).find('input[type="text"]').each(function() {
      if ($(this).attr('value') == '') {
        errors += 1;
      }
    });
    if (errors > 0) {
      alert('Uh-oh. We need your email address in order to send you our email newsletter. Thanks!');
      return false;
    }
  });
  // Toggle for contact form
  $('.contact #content form .nested input[type="checkbox"]').change(function() {
    if ($(this).is(':checked')) {
      $(this).closest('li').addClass('expanded');
    } else {
      $(this).closest('li').removeClass('expanded');
    }
  });
  // Reroute if it's a support request
  // $('#support-request').change(function() {
  //   if ($(this).is(':checked')) {
  //     // $(this).closest('form').attr('action', 'http://urbanairship.com');
  //     alert('Hey, feed me the right place to post this form to!');
  //   } else {
  //     $(this).closest('form').attr('action', 'http://lfov.net/webrecorder/f');
  //   }
  // });
  
  // Resource downloads
  $("a.resource-download").click(function(event) {
    event.preventDefault();
    if (!$.cookie('urbanairship_downloads')) {
      // Save the targeted file for use later
      $.cookie('urbanairship_download', $(this).attr('href'), { expires: 365, path: '/', domain: '.urbanairship.com'});
      // Pop up the form
      $.fancybox({href: "/wp-content/themes/urbanairship/form-resources.php", type: "ajax"});
    } else {
      // Track the download in Pardot
      trackLink($(this));
      // Open the download in a new tab/window
      window.open($(this).attr('href'), '_blank');
    }
  });
  // For Pardot Tracking on a link
  function trackLink(link) {
    var pageURL = $(link).attr('href').replace("http://" + location.hostname, "");
    piIncludeInActivities = true;
    piTracker(pageURL);
  }
  // For getting user information on the first resource download
  $("#resource-form form").live('submit', function(event) {
    if (simpleValidation(this)) {
      // Set a cookie allowing them to download files without filling out the form again
      $.cookie('urbanairship_downloads', 'Ready for takeoff!', { expires: 365, path: '/', domain: '.urbanairship.com'});
      // Set the cookie that will get them back to this resource page from the generic routing thank you page
      $.cookie('urbanairship_referring_page', document.location.pathname + '?thanks', { expires: 365, path: '/', domain: '.urbanairship.com'});
      // Track the download in Pardot
      trackLink($('a[href*="' + $.cookie('urbanairship_download') + '"]').first());
      // Open the download in a new tab/window
      window.open($.cookie('urbanairship_download'), '_blank');
      // Submit the form
      return true;
    } else {
      // Don't submit the form
      return false;
    }
  });
  
  // Applying simple validation for forms
  $("form.validated, form.wpcf7-form").live('submit', function() {
    return simpleValidation(this);
  });
  
  // Fancybox
  $('a[rel="lightbox"]').each(function() {
    var options = {},
        width = $(this).attr('data-target-width'), 
        height = $(this).attr('data-target-height');
    if (width != undefined || height != undefined) {
      options.autoScale = false;
      options.autoDimensions = false;
      // options.type = 'inline';
      options.width = (width != undefined) ? (parseInt(width) + 16) : Math.floor($(window).width() * 0.9);
      options.height = (height != undefined) ? (parseInt(height) + 16) : Math.floor($(window).height() * 0.9);
    }
    $(this).fancybox(options);
    return false;
  });
  
    // add fancybox to wordpress galleries
    $('.gallery').each(function() {
        var relID = $(this).attr('id');
        var gallerylink = $(this).find('.gallery-item a');
        $(gallerylink).attr('rel',relID).addClass('grouped_elements');
        $('a.grouped_elements').fancybox({
            'cyclic'                :   true,
    		'height'                :   'auto',
            'hideOnOverlayClick'    :   true,
            'margin'                :   0,
            // 'overlayShow'           :   false,
            'overlayColor'          :   '#000',
            'overlayOpacity'        :   0.2,
            'padding'               :   0,
    		'speedIn'               :   400,
    		'speedOut'              :   200,
            'titleShow'             :   true,
            'transitionIn'          :   'fade',
    		'transitionOut'         :   'fade',
            'type'                  :   'image',
    		'width'                 :   'auto'
        });
    });
  
    
      
  // Tweet widgets for the media relation section
  $("#tweets").tweet({
    username: "urbanairship",
    retweets: false,
    avatar_size: 32,
    count: 3,
    intro_test: false,
    join_text: false,
    outro_text: false,
    loading_text: "loading tweets...",
    template: "{text} {time}"
  });
  
  // Track Google Analytics events
  // -- General function. Expects a tag with the class "track" and three additional attributes: data-category, data-action, and data-label
  $('.track').track({
    category: function(element) {
      return $(element).attr('data-category');
    },
    action: function(element) {
      return $(element).attr('data-action'); 
    },
    label: function(element) {
      return $(element).attr('data-label'); 
    }
  });
  
  // Specific tracking bits
  $('a.product-sheet').track({category: "CTA Button", action: "CTA Click", label: "CTA 1 - Download PDF Product Sheet"});
  $('a.create-account-push').track({category: "CTA Button", action: "CTA Click", label: "CTA 2 - Create an Account - Push"});
  $('a.create-account-rich-push').track({category: "CTA Button", action: "CTA Click", label: "CTA 3 - Create an Account - Rich Push"});
  $('a.create-account-subscription').track({category: "CTA Button", action: "CTA Click", label: "CTA 4 - Create an Account - In-app Subscriptions"});
  $('a.create-account-inapp').track({category: "CTA Button", action: "CTA Click", label: "CTA 6 - Create an Account - In-app Purchases"});
  $('a.create-account-reports').track({category: "CTA Button", action: "CTA Click", label: "CTA 7 - Create an Account - Reports"});
  $('a.create-account-composer').track({category: "CTA Button", action: "CTA Click", label: "CTA 8 - Create an Account - Push composer"});
  $('a.contact-sales').track({category: "CTA Button", action: "CTA Click", label: "CTA 5 - Contact Sales"});
  $('a.homepage-tour').track({category: "Homepage", action: "Tour Click", label: "Urban Airship Revenge"});
  $('.pricing #push-pricing a[href="https://go.urbanairship.com/accounts/register/"]').track({category: "Pricing", action: "Push Sign Up Now Click"});
  $('.pricing #push-pricing a[href="/company/contact/"]').track({category: "Pricing", action: "Push Contact Sales Click"});
  $('.pricing #inapp-pricing a[href="https://go.urbanairship.com/accounts/register/"]').track({category: "Pricing", action: "Push Contact Sales Click"});
  $('#footer .twitter a').track({category: "Social Media", action: "Offsite Link", label: "Twitter"});
  $('#footer .youtube a').track({category: "Social Media", action: "Offsite Link", label: "YouTube"});
  $('#footer .linkedin a').track({category: "Social Media", action: "Offsite Link", label: "LinkedIn"});
  $('.page-id-1657 #guts a').track({category: "Resources", action: "Resource Link", label: function(element) { return $(element).text(); } });
  $('a.resources-best-practices-link').track({category: "Resources", action: "Best Practices", label: function(element) { return "Link - " + $(element).text(); } });
  $('a.resources-best-practices-pdf').track({category: "Resources", action: "Best Practices", label: function(element) { return "PDF - " + $(element).text(); } });
  // Track Events on Dynamically Generated Elements
  $('#heros #about .player a').live('click', function() {
  	$(this).track({category: "Homepage", action: "Video Click", label: "Urban Airship 101 Video"});
  });
  $('#heros #push a[href*="/products/push/"]').live('click', function() {
  	$(this).track({category: "Homepage", action: "Explore Push Click"});
  });
  $('#heros #push a[href*="/products/rich-push/"]').live('click', function() {
  	$(this).track({category: "Homepage", action: "Explore Rich Push Click"});
  });
  $('#heros #premium a[href*="/products/push-composer/"]').live('click', function() {
  	$(this).track({category: "Homepage", action: "Explore Composer Click"});
  });
  $('#heros #premium a[href*="/products/reports/"]').live('click', function() {
  	$(this).track({category: "Homepage", action: "Explore Reports Click"});
  });
  $('#heros #premium a[href^="https://go.urbanairship.com"]').live('click', function() {
  	$(this).track({category: "Homepage", action: "Sign Up Now Click"});
  });
  $('#heros #geopush a').live('click', function() {
  	$(this).track({category: "Homepage", action: "Geo-push Click"});
  });

  // $('a.google-groups-link').track({category: "Offsite", action: "Offsite Link", label: "Google Groups"});
  // $('a.irc-channel-link').track({category: "Offsite", action: "Offsite Link", label: "IRC Channel"});
  // $('a.support-email-link').track({category: "Offsite", action: "Offsite Link", label: "Email Support"});
  
  
  var ua = navigator.userAgent,
      watched_event = (ua.match(/iPad/i) || ua.match(/iPhone/i)) ? "touchstart" : "click";
  
  $('#navigation li.current-menu-item, #navigation li.current-page-ancestor').live(watched_event, function(event) {
    if (window.innerWidth <= 480) {
      event.preventDefault();
      $('#navigation').toggleClass('expanded');
    }
  });
  var watchPopup = function(popup) {
    $(document).bind(watched_event, function(element) {
      if ($(element.target).parents(popup).length == 0 ) {
        $(popup).removeClass('expanded');
      }
    });
  };
  watchPopup('#navigation');
  
  //Set first navigation item if necessary
  if (window.innerWidth <= 480 && $('#navigation li.current-menu-item, #navigation li.current-page-ancestor').length == 0) {
    $('#navigation li').first().clone().addClass('current-menu-item').prependTo('#navigation').find('a').attr('href', '#').find('span').text('Select...');
  }
    
});
