/* Author: The Atom Group

*/

var WSF = {
  conjugations: { "does": "do", "wants": "want", "has": "have", "is": "am" },
  findYourSportFacets: ['description', 'time', 'money', 'fitness'],
  findYourSportSliderConfig: {
    controls: false,
    pager: true,
    infiniteLoop: false,
    displaySlideQty: 3,
    moveSlideQty: 3,
    pagerSelector: '.sport-recommendations .pagination .pager',
    pagerActiveClass: 'active',
    onAfterSlide: function (currentSlideNum, numSlides, currentSlideObject) {
      if (numSlides > 3) {
        jQuery(".sport-recommendations a.prev, .sport-recommendations a.next").removeClass("disabled");
      }
      if (currentSlideNum === 0) {
        jQuery(".sport-recommendations a.prev").addClass("disabled");
      } else if (currentSlideNum >= numSlides - 3) { // 3 columns per page and the last page isn't always full
        jQuery(".sport-recommendations a.next").addClass("disabled");
      }
    }
  }
};

jQuery(document).ready(function () {
  // To resolve a conflict with prototype.js
  jQuery.noConflict();
  /**
  * Main Navigation
  */

  // TODO make this keyboard-accessible
  jQuery('#main-nav > ul').find('> li').hover(function () {
    jQuery(this).find('ul')
        .stop(true, true).slideToggle('fast');
  });

  /**
  * Donate Bar
  */
  if (jQuery('.foot-bar').length > 0) {
    var 
        footBar = jQuery('.foot-bar'),
        fb = footBar.find('a.facebook'),
        twitter = footBar.find('a.twitter'),
        instapaper = footBar.find('a.instapaper'),
        email = footBar.find('a.email'),
        print = footBar.find('a.print'),
        documentUrl = document.location.href;

    fb.live('click', shareOnFacebook);
    twitter.live('click', shareOnTwitter);
    instapaper.live('click', shareOnInstapaper);
    print.live('click', function (e) { e.preventDefault(); window.print(); });
    email.attr('href', 'mailto:?body=' + documentUrl);
  }


  /**
  * Home Slide
  */
  WSF.homeSlider = jQuery('#slides').bxSlider({
    auto: true,
    pause: 8000,
    controls: false,
    pager: true,
    pagerSelector: 'div.slide-nav div.pager',
    pagerActiveClass: 'active',
    onBeforeSlide: function (currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
      var 
            $image = jQuery('div.slide-image'),
            $inactiveImage = $image.not('.active'),
            $activeImage = jQuery('div.slide-image.active'),
            $imageUrl = encodeURI(jQuery(currentSlideHtmlObject).find('img.preload').attr('src').replace(/"/g, ''));

      $inactiveImage.css('background-image', 'url(' + $imageUrl + ')').show();

      $activeImage.fadeOut(function () {
        $activeImage.insertBefore('div.slide-image:not(.active)');
        $image.toggleClass('active');
      });
    }
  });

  if (jQuery("#slideshow").length === 1) {
    WSF.homeSlider.goToFirstSlide(); //otherwise we wait 8 seconds for the onBeforeSlide to fire and the background image to show
  }

  jQuery('#slideshow a.slide-left').click(function () {
    WSF.homeSlider.goToPreviousSlide();
    return false;
  });

  jQuery('#slideshow a.slide-right').click(function () {
    WSF.homeSlider.goToNextSlide();
    return false;
  });


  /**
  * Find Your Sport Page
  */
  if (jQuery(".find-your-sport").length === 1) {

    // When the page loads, hide the personalized content
    jQuery(".sport-recommendations").hide();
    jQuery(".questions input:radio:checked").removeAttr('checked');

    jQuery('.sport-recommendations a.prev').live('click', function (e) {
      e.preventDefault();
      WSF.findYourSportSlider.goToPreviousSlide();
    });

    jQuery('.sport-recommendations a.next').live('click', function (e) {
      e.preventDefault();
      WSF.findYourSportSlider.goToNextSlide();
    });

    jQuery('.sport-recommendations a.hide-button').live('click', function (e) {
      e.preventDefault();
      if (WSF.findYourSportSlider.getSlideCount() > 1) {

        slideNumber = WSF.findYourSportSlider.getCurrentSlide();
        slideCount = WSF.findYourSportSlider.getSlideCount() - 1;

        jQuery(this).parents("li.pager").remove();

        jQuery(".sport-recommendations a.pager-link").remove();
        WSF.findYourSportSlider.reloadShow();

        if (slideNumber >= slideCount) {
          WSF.findYourSportSlider.goToSlide(slideCount - 1);
        } else if (slideNumber === 0) {
          WSF.findYourSportSlider.goToSlide(0);
        } else {
          WSF.findYourSportSlider.goToSlide(slideNumber);
        }
      } else {

        // if length == 0, no results found
      }
    });

    // Form controls
    jQuery(".find-your-sport label").click(function (e) {

      jQuery(this).children("input[type='radio']").attr("checked", "checked");

      if (jQuery(this).parents(".info-block-chooser").length === 1) {
        jQuery(this).addClass("selected").removeClass("not-selected").siblings("label").removeClass("selected").addClass("not-selected");
      } else {
        sliderValue = 25 + (jQuery(this).prevAll("label").length) * 50; // middle of each range: 25, 75, 125, 175
        jQuery(this).addClass("selected").siblings("label").removeClass("selected").siblings(".slider").slider("value", sliderValue);
      }

      if (jQuery(".questions input:radio:checked").length > 0) {
        jQuery(".questions .blueBtn").removeClass("disabled");
      }
    });

    jQuery(".slider").slider({
      range: "min",
      value: 1,
      min: 1,
      max: 200,
      slide: function (e, ui) {
        labels = jQuery(e.target).nextUntil(":not(label)").removeClass("selected");
        selectedLabelIndex = 0;

        switch (true) {
          case (ui.value < 50):
            selectedLabelIndex = 0;
            break;
          case ((ui.value >= 50) && (ui.value < 100)):
            selectedLabelIndex = 1;
            break;
          case ((ui.value >= 100) && (ui.value < 150)):
            selectedLabelIndex = 2;
            break;
          case (ui.value >= 150):
            selectedLabelIndex = 3;
            break;
        }

        //can we always count on the user agent to deselect other inputs?
        jQuery(labels).eq(selectedLabelIndex).addClass("selected").children("input").attr("checked", "checked");
        if (jQuery(".questions input:radio:checked").length > 0) {
          jQuery(".questions .blueBtn").removeClass("disabled");
        }
      }
    });

    jQuery(".find-your-sport .blueBtn").click(function (e) {
      e.preventDefault();
      if (jQuery(this).parents(".questions").length === 1) {
        if (jQuery(".questions input:radio:checked").length > 0) {
          showFindASportResults();
        } else {
          //error message?

        }
      } else { // show questions, hide results
        jQuery(".sport-recommendations").hide();
        // fixes an issue with the sliders in IE7
        jQuery(".questions").slideDown(function () { jQuery('.questions .slider-container input:checked').click(); });
      }

    });


  } // end Find Your Sport functionality

  /**
  * Find a Solution
  */
  if (jQuery(".find-a-solution").length === 1) {
    jQuery(".find-a-solution select").hide();
    jQuery("div.problem .current-value, div.problem li").each(function (i) {
      //save the original verb form
      jQuery(this).data("verb", jQuery(this).text().split(" ")[0]);
    });
    jQuery(".find-a-solution .select-box").css("display", "inline-block");
    jQuery("select").each(function () {
      jQuery(this).children("option").first().attr("selected", "selected");
    });

    jQuery(".find-a-solution select.affected-person").change(function (e) {
      jQuery("label#problem-label").empty().append(jQuery(this).children(":selected").data("sentence-part"));
      jQuery("#sentence-article").empty().append(jQuery(this).children(":selected").data("sentence-article"));
      if (jQuery(this).children(":selected").data("sentence-part") === 'I' || jQuery(this).children(":selected").data("sentence-part") === 'you') {
        // use the alternate form
        jQuery("div.problem .current-value, div.problem li").each(function (i) {
          sentenceArray = jQuery(this).text().split(" ");
          verb = jQuery(this).data("verb");
          sentenceArray[0] = WSF.conjugations[verb];
          jQuery(this).text(sentenceArray.join(" "));
        });
      } else {
        //use the original form
        jQuery("div.problem .current-value, div.problem li").each(function (i) {
          sentenceArray = jQuery(this).text().split(" ");
          sentenceArray[0] = jQuery(this).data("verb");
          jQuery(this).text(sentenceArray.join(" "));
        });
      }
    });

    jQuery("input[type=submit]").click(function (e) {
      e.preventDefault();
      jQuery(".hidden.person").val(jQuery("select").first().val());
      jQuery(".hidden.problem").val(jQuery("select").last().val());
      jQuery("form:first").submit();
    });
}

jQuery(".find-a-solution select.affected-person").trigger('change')// init the drop down.
  //end Find a Solution

  /**
  * Explore Further Slide
  */

  WSF.exploreFurtherSlider = jQuery('#explore-further-carousel').bxSlider({
    controls: false,
    pager: false,
    displaySlideQty: 2
  });

  jQuery('div.carousel a.prev').click(function () {
    WSF.exploreFurtherSlider.goToPreviousSlide();
    return false;
  });

  jQuery('div.carousel a.next').click(function () {
    WSF.exploreFurtherSlider.goToNextSlide();
    return false;
  });

  /**
  * Sport page
  */
  if (jQuery("#sport-athletes ul#athlete-grid li").length > 2) {
    WSF.athleteGridSmallSlider = jQuery('#sport-athletes ul#athlete-grid').bxSlider({
      controls: false,
      pager: false,
      displaySlideQty: 2
    });

    jQuery('#sport-athletes a.prev').click(function (e) {
      e.preventDefault();
      WSF.athleteGridSmallSlider.goToPreviousSlide();
    });

    jQuery('#sport-athletes a.next').click(function (e) {
      e.preventDefault();
      WSF.athleteGridSmallSlider.goToNextSlide();
    });
  } else if (jQuery('#sport-athletes ul#athlete-grid')) {
    jQuery('#sport-athletes a.blueBtn').hide();
  }



  /**
  * Find an Athlete
  */

  // save the grid for later
  jQuery("body").data("all-sports", jQuery("#athlete-grid").html());

  WSF.ourAthletesSlider = jQuery('#find-an-athlete #athlete-grid').bxSlider({
    controls: false,
    pager: true,
    pagerSelector: '#find-an-athlete div.pagination div.dots',
    pagerActiveClass: 'active',
    displaySlideQty: 4,
    moveSlideQty: 4,
    infiniteLoop: false,
    onAfterSlide: function (currentSlideNum, numSlides, currentSlideObject) {
      if (currentSlideNum === 0) {
        jQuery("#find-an-athlete a.prev").addClass("disabled");
      } else if (currentSlideNum >= numSlides - 4) { // 4 columns per page and the last page isn't always full
        jQuery("#find-an-athlete a.next").addClass("disabled");
      } else {
        jQuery("#find-an-athlete a.blueBtn").removeClass("disabled");
      }
    }
  });



  jQuery('#find-an-athlete  a.prev').click(function () {
    WSF.ourAthletesSlider.goToPreviousSlide();
    return false;
  });

  jQuery('#find-an-athlete a.next').click(function () {
    WSF.ourAthletesSlider.goToNextSlide();
    return false;
  });

  if (!Modernizr.csstransitions) {
    jQuery('#athlete-grid div a').bind('focusin focusout mouseenter mouseleave', function (e) {
      if (e.type === "mouseenter" || e.type === "focusin") {
        jQuery(this).find('div.overlay').animate({
          height: '121px',
          top: '0px'
        }, 500);
      } else {
        jQuery(this).find('div.overlay').animate({
          height: '22px',
          top: '99px'
        }, 500);
      }
    });
  }

  /* TODO keyboard/screenreader access (make <li> focusable, don't use display: none) 
  test in other browsers
  better title attrib in html
  */


  jQuery("*[aria-labelledby]").each(function (i, el) {
    var labelID = "#" + jQuery(this).attr("aria-labelledby");
    jQuery(labelID).click(function (e) { jQuery(el).focus(); });
  });


  if (jQuery("#find-an-athlete").length === 1) {

    var sportList = new Array();
    jQuery("#find-an-athlete .overlay p").each(function (i, el) {
      if (jQuery.inArray(jQuery(el).text(), sportList) === -1) {
        sportList.push(jQuery(el).text());
      }
    });

    sportList.sort();

    for (i = 0; i < sportList.length; i++) {
      jQuery('#find-an-athlete .select-box ol').append('<li role="option">' + sportList[i] + '</li>');
    }



    jQuery("#find-an-athlete .filter-controls").removeClass("invisible");
  } // end if find-an-athlete


  /**
  * CUSTOM SELECT BOX HANDLER
  * NOTES:
  *  IE8 sees focusin instead of click on initial selection
  *  IE7 fires several extra events - delays final reaction
  */

  jQuery('.select-box').bind('focusin focusout click keydown', function (e) {
    if (e.type === "focusin") {
      jQuery(this).addClass("has-focus");

    } else if (e.type === "click") {
      e.preventDefault();
      if (jQuery(this).hasClass("open") && jQuery(e.target).parent("ol").length === 1) {
        jQuery(this).children('.current-value').empty().append(jQuery(e.target).text());
        jQuery(this).children('.current-value').data("verb", jQuery(e.target).data("verb"));
        jQuery(this).find(".focused").removeClass("focused");
        jQuery(e.target).addClass("focused");
        jQuery(this).removeClass("open");
      } else {
        jQuery(this).toggleClass("open");
        return false; //do not filter elements again
      }

    } else if (e.type === "focusout" && jQuery(e.target).parents(".select-box").length === 0) {
      // to fix IE problem where this fired *on the list items!*

      jQuery(this).removeClass("open has-focus");

    } else if (e.type === "keydown") {
      if (e.which === 27) { //ESC
        jQuery(this).removeClass("open");
        return false; //this should skip the rest of the function
      } else if (e.which === 32 || e.which === 13) { //enter or spacebar
        //close dropdown and set currently focused value to selected
        jQuery(this).removeClass("open");
      } else if (e.which > 36 && e.which < 41) { //an arrow key

        var toFocus;

        if (e.which === 38 || e.which === 37) { // left or up - show prev
          toFocus = jQuery(this).find(".focused").prev().length === 0 ? jQuery(this).find(".focused").siblings().last() : jQuery(this).find(".focused").prev();
        } else if (e.which === 39 || e.which === 40) { // right or down - show next
          toFocus = jQuery(this).find(".focused").next().length === 0 ? jQuery(this).find(".focused").siblings().first() : jQuery(this).find(".focused").next();
        }

        if (toFocus) {
          jQuery(this).find(".focused").removeClass("focused");
          jQuery(toFocus).addClass("focused");
          jQuery(this).children('.current-value').empty().append(jQuery(toFocus).text());
          jQuery(this).children('.current-value').data("verb", jQuery(toFocus).data("verb"));
        }

        return false; // do not filter on arrow key press, do not scroll page

      } else {
        // do nothing if it is any other key (but we should take letters, pg up/down, home/end)
      }
    }

    if (jQuery("#find-an-athlete").length === 1) {
      var filterTerm = jQuery.trim(jQuery(".focused").text());

      UXServices.GetAthleteGrid(filterTerm.toLowerCase(), function (html) {
        if (html !== "" || filterTerm === "All Sports") { //otherwise there are really no entries to show
          if (filterTerm === "All Sports") {
            html = jQuery("body").data("all-sports");
          }

          numAthletes = jQuery(html).find(".overlay").length;
          jQuery("#athlete-grid").empty();

          if (numAthletes > 12) {
            jQuery("#athlete-grid").append(html);
            jQuery("#athlete-grid").children("li").addClass("pager"); // if class=pager is missing, page hangs
            jQuery("#find-an-athlete .dots").empty();
            WSF.ourAthletesSlider.reloadShow();
            jQuery("#find-an-athlete .pagination").show();
          } else {
            // don't bother to reload the show - don't need pagination

            jQuery("#athlete-grid").css("left", 0).css("width", "auto").append(jQuery(html).find("div:not(.overlay)"));
            jQuery("#athlete-grid div:not(.overlay)").wrap('<li></li>');
            jQuery("#find-an-athlete .pagination").hide();
          }
        }
      }); // end UXServices
    } else { // not athlete-grid
      // we should make the same selection on the form's select box
      // assumes that corresponding select is immediately before, has options in same order
      jQuery(this).prev().children("option").eq(jQuery(this).find(".focused").prevAll("li").length).attr("selected", "selected");
      jQuery(this).prev().change();
    }
  }); // end .select-box listener


});                                                                               // end doc onready

/**
 * Share URL
 */
/*twitter*/
function shareOnTwitter() { window.twttr = window.twttr || {}; var D = 550, A = 450, C = screen.height, B = screen.width, H = Math.round((B / 2) - (D / 2)), G = 0, F = document, E; if (C > A) { G = Math.round((C / 2) - (A / 2)) } window.twttr.shareWin = window.open('http://twitter.com/share', '', 'left=' + H + ',top=' + G + ',width=' + D + ',height=' + A + ',personalbar=0,toolbar=0,scrollbars=1,resizable=1'); E = F.createElement('script'); E.src = 'http://platform.twitter.com/bookmarklets/share.js?v=1';F.getElementsByTagName('head')[0].appendChild(E);return false; }
/*facebook*/
function shareOnFacebook() { u = location.href; t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }
/*instapaper*/
function shareOnInstapaper() { u = location.href; t = document.title; window.open('http://www.instapaper.com/hello2?url=' + encodeURIComponent(u) + '&title=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=792,height=590'); return false; }

// Find a Sport Tool results
function showFindASportResults() {
  if (jQuery(".questions input:radio:checked").length > 0) {   // some fields filled - reveal results

    var selectedOptions = [];
    jQuery(".questions input:radio:checked").each(function () {
      selectedOptions.push(jQuery(this).data("sentence-part"));
    });
    jQuery(".sport-recommendations span.interpolate").text(selectedOptions.join(', '));

    var answers = [];
    for (i = 0; i < WSF.findYourSportFacets.length; i++) {
      sport = WSF.findYourSportFacets[i];
      // 5 ensures that sport_facet_val < slider_val will always be true for unset sliders
      answers[sport] = (jQuery(".questions input[name=" + sport + "]:checked").val() === undefined) ? 5 : jQuery(".questions input[name=" + sport + "]:checked").val();
    }

    if (WSF.findYourSportSlider) { WSF.findYourSportSlider.destroyShow(); }
    jQuery(".sport-recommendations .carousel ul").empty();


    jQuery('#full-sport-list li').filter(function (i) {
      for (j = 0; j < WSF.findYourSportFacets.length; j++) {
        key = WSF.findYourSportFacets[j];
        //console.log(key + " " + answers[key]);
        if (jQuery(this).data(key) > answers[key]) { return false; }
      }
      return true;
    }).clone().appendTo(".sport-recommendations .carousel ul");

    jQuery(".sport-recommendations .num-results").text(jQuery(".sport-recommendations .carousel ul li").length);

    jQuery(".sport-recommendations a.prev").addClass("disabled");

    if (jQuery(".sport-recommendations .carousel li").length <= 3) {
      jQuery(".sport-recommendations .pagination").hide();
    } else { 
      jQuery(".sport-recommendations .pagination").show();
    }

    jQuery(".questions").slideUp();
    jQuery(".sport-recommendations").show();

    if (jQuery(".sport-recommendations .carousel li").length > 0) {
      jQuery(".sport-recommendations a.pager-link").remove();
      WSF.findYourSportSlider = jQuery('.find-your-sport .carousel ul').bxSlider(WSF.findYourSportSliderConfig);
    } else {
      // if length == 0, no results found
    }

    jQuery("html").scrollTop(450); // firefox + IE
    jQuery("body").scrollTop(450); //webkit

  }
}
